// 统一的 WS 指令处理分发表（按功能模块分组，注释说明 code 作用）
// 返回格式统一为 { act_id, code: 0, msg: "", data }（除非特别说明）

import { SystemMessageEntity } from "../entities/system-message.entity";
import { mountWsHandlers } from "./mount-ws-handlers";
export type WsHandler = (
  payload: any,
  helpers: {
    userId: number; // 用户ID，连接时已验证
    selectedCharacterId?: number; // 当前选择的角色ID
    getUserToken: (uid: number) => Promise<string>;
    getUserRoles: (uid: number) => Promise<any[]>; // 修复类型为Promise
    updateSelectedCharacter: (
      characterId: number,
      roleName: string
    ) => Promise<void>; // 新增
    newRoleId: () => number;
    characterService: any; // CharacterService实例
    redisService: any; // RedisService实例
    chatMessageService: any; // ChatMessageService实例
    privateMessageService: any; // PrivateMessageService实例
    announcementService: any; // AnnouncementService实例
    itemService: any; // ItemService实例
    basicItemService: any; // BasicItemService实例
    inventoryService: any; // InventoryService实例
    characterMedicineService: any; // CharacterMedicineService实例
    characterEquipmentInventoryService: any; // CharacterEquipmentInventoryService实例
    equipmentBaseService: any; // EquipmentBaseService实例
    monthlyCardService: any; // MonthlyCardService实例
    characterSkillService: any; // CharacterSkillService实例
    shopService: any; // ShopService实例
    deputyGeneralService: any; // DeputyGeneralService实例
    bankService: any; // BankService实例
    casinoService: any; // CasinoService实例
    mapAreaService: any; // MapAreaService实例
    locationService: any; // CharacterLocationService实例
    npcService: any; // NpcService实例
    mountBaseService: any; // MountBaseService实例
    characterMountService: any; // CharacterMountService实例
    mountLevelExperienceService: any; // MountLevelExperienceService实例
    gemService: any; // GemService实例
    talentStoneService?: any; // TalentStoneService实例
    stallService?: any; // 摊位服务
    pushMessage: (message: any) => void; // 主动推送消息
    sendCharacterLocationInfo: (characterId: number) => void;
    pushPrivateMessageNotification?: (
      receiverCharacterId: number,
      senderCharacterId: number,
      messageType: number
    ) => void; // 推送私信通知
    wsGateway?: any; // WebSocketGateway实例
    systemMessageService: any; // SystemMessageService实例
    characterAttributeService: any; // CharacterAttributeService实例
    characterEquipmentService: any; // CharacterEquipmentService实例
    playerOnlineTimeService: any; // PlayerOnlineTimeService实例
    deputyAttributeService?: any; // DeputyAttributeService实例
    vipService?: any; // VipService实例
    playerStatusService?: any; // PlayerStatusService 实例
    houseTrainingService?: any; // HouseTrainingService 实例
    goldTradeService?: any; // GoldTradeService 实例
  }
) => Promise<any> | any;

export const wsHandlers: Record<number, WsHandler> = {
  // 1515：书房开始训练（兼容两种前端入参格式）
  1515: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1515, code: -1, msg: "请先选择角色" };
      const svc = (helpers as any).houseTrainingService;
      const hasCountMode =
        typeof payload?.l !== "undefined" || typeof payload?.c !== "undefined";
      if (hasCountMode) {
        const level = Number(payload?.l || 0);
        const count = Number(payload?.c || 0);
        return await svc.startLibraryTrainingByCount({
          characterId,
          level,
          count,
        });
      } else {
        const level = Number(payload?.level ?? 0);
        const duration = Number(payload?.duration ?? 0);
        return await svc.startLibraryTraining({ characterId, level, duration });
      }
    } catch (error: any) {
      return { act_id: 1515, code: -1, msg: error?.message || "开始训练失败" };
    }
  },
  // 1520：功房修炼副将心法（l=心法等级索引1-4，c=数量；id 暂不校验）
  1520: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1520, code: -1, msg: "请先选择角色" };
      const levelIndex = Number(payload?.l || 0);
      const count = Number(payload?.c || 0);
      const svc = (helpers as any).houseTrainingService;
      const res = await svc.startGongfangTrainingByCount({
        characterId,
        levelIndex,
        count,
      });
      return res;
    } catch (error: any) {
      return { act_id: 1520, code: -1, msg: error?.message || "开始修炼失败" };
    }
  },

  // 1109：查询副将战斗能力（仅副将装备的天赋石抗性，逻辑在服务中）
  1109: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1109, code: -1, msg: "请先选择角色", data: null };
      }

      const deputyId = Number(payload?.id || 0);
      if (!Number.isFinite(deputyId) || deputyId <= 0) {
        return { act_id: 1109, code: -1, msg: "副将ID不能为空", data: null };
      }

      // 所属校验：副将必须属于当前玩家
      const belongs =
        await helpers.deputyGeneralService.playerDeputyRepository?.findOne({
          where: { deputy_id: deputyId, player_id: characterId },
        });
      if (!belongs) {
        return {
          act_id: 1109,
          code: -1,
          msg: "副将不属于当前玩家",
          data: null,
        };
      }

      const data =
        await helpers.deputyGeneralService.calculateDeputyResistancesFromStones(
          characterId,
          deputyId
        );

      return {
        act_id: 1109,
        code: 0,
        data,
      };
    } catch (error) {
      return {
        act_id: 1109,
        code: -1,
        msg: (error as Error)?.message || "查询战斗能力失败",
        data: null,
      };
    }
  },

  // 6406：炼丹房开始炼制（魂元丹421, 60分钟）
  6406: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 6406, code: -1, msg: "请先选择角色" };
      const svc = (helpers as any).houseTrainingService;
      if (typeof payload?.c !== "undefined") {
        const count = Number(payload?.c || 0);
        return await svc.startAlchemyTrainingByCount({ characterId, count });
      } else {
        const itemId = Number(payload?.itemId ?? 0);
        const duration = Number(payload?.duration ?? 0);
        return await svc.startAlchemyTraining({
          characterId,
          itemId,
          duration,
        });
      }
    } catch (error: any) {
      return { act_id: 6406, code: -1, msg: error?.message || "开始炼丹失败" };
    }
  },
  // 100：区域信息（与登录后主动推送格式一致）
  100: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 100, code: -1, msg: "请先选择角色" };
      }
      const playerStatusService = (helpers as any).playerStatusService;
      if (playerStatusService?.buildAct100) {
        return await playerStatusService.buildAct100(characterId, {
          characterLocationService: helpers.locationService,
        });
      }
      return { act_id: 100, code: -1, msg: "服务未准备好" };
    } catch (error: any) {
      return { act_id: 100, code: -1, msg: error?.message || "查询失败" };
    }
  },
  // 300：查询角色状态（与登录后主动推送格式一致）
  300: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 300, code: -1, msg: "请先选择角色" };
      }

      // 统一由公共服务构建 300 消息
      const playerStatusService = (helpers as any).playerStatusService;
      if (playerStatusService?.buildAct300) {
        return await playerStatusService.buildAct300(characterId, {
          characterService: helpers.characterService,
          characterAttributeService: helpers.characterAttributeService,
          vipService: (helpers as any).vipService,
        });
      }

      // 兜底（不应走到这里）
      return { act_id: 300, code: -1, msg: "服务未准备好" };
    } catch (error: any) {
      return { act_id: 300, code: -1, msg: error?.message || "查询失败" };
    }
  },
  // 1264：跳蚤市场分类刷选/摊位列表
  1264: async (payload, helpers) => {
    const type = Number(payload?.type ?? 0);
    const pageNum = Number(payload?.pageNum ?? 0);
    const list = await (helpers as any).stallService.listByType({
      type,
      pageNum,
    });
    return { act_id: 1264, code: 0, list };
  },

  // 重复定义的 1269（移除）

  // 6008：矿石背包列表
  6008: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId || 0;
      if (!characterId) return { act_id: 6008, code: -1, msg: "请先选择角色" };
      const pageNum = Number(payload?.pageNum || 0);
      const list = await helpers.inventoryService.getMineralList(
        characterId,
        pageNum
      );
      return { act_id: 6008, code: 0, msg: "ok", list };
    } catch (error: any) {
      return {
        act_id: 6008,
        code: -1,
        msg: error?.message || "查询失败",
        data: null,
      };
    }
  },

  // 1311：查看我的摊位
  1311: async (_payload, helpers) => {
    const roleId = helpers.selectedCharacterId;
    if (!roleId) return { act_id: 1311, code: 8, msg: "您还没创建摊位" };
    const roleName =
      (await helpers.characterService.getCharacterById(roleId))?.name || "";
    const data = await (helpers as any).stallService.queryMyStall(
      roleId,
      roleName
    );
    return { act_id: 1311, code: 0, data };
  },

  // 1315：修改我的摊位名字
  1315: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId;
    if (!roleId) return { act_id: 1315, code: -1, msg: "请先选择角色" };
    const name = String(payload?.name || "");
    await (helpers as any).stallService.rename(roleId, name);
    return { act_id: 1315, code: 0 };
  },

  // 1325：我的摊位添加预上架物品（从背包/药品扣减）
  1325: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId;
    if (!roleId) return { act_id: 1325, code: -1, msg: "请先选择角色" };
    const id = Number(payload?.id);
    const pos = Number(payload?.pos);
    const count = Number(payload?.count);
    const money = Number(payload?.money);
    await (helpers as any).stallService.prepareShelfFromInventory(roleId, {
      id,
      pos,
      count,
      money,
    });
    return { act_id: 1325, code: 0 };
  },

  // 1326：上架装备（从装备背包移除该条记录，写入摊位）
  1326: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId;
    if (!roleId) return { act_id: 1326, code: -1, msg: "请先选择角色" };
    const id = Number(payload?.id);
    const pos = Number(payload?.pos);
    const money = Number(payload?.money || 0);
    await (helpers as any).stallService.prepareShelfEquipment(roleId, {
      id,
      pos,
      money,
    });
    return { act_id: 1326, code: 0 };
  },

  // 1327：上架宝石（从宝石背包移除该条记录，写入摊位）
  1327: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId;
    if (!roleId) return { act_id: 1327, code: -1, msg: "请先选择角色" };
    const id = Number(payload?.id);
    const pos = Number(payload?.pos);
    const money = Number(payload?.money || 0);
    await (helpers as any).stallService.prepareShelfGem(roleId, {
      id,
      pos,
      money,
    });
    return { act_id: 1327, code: 0 };
  },

  // 1317：删除对应架位物品（退回对应背包/表）
  1317: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId;
    if (!roleId) return { act_id: 1317, code: -1, msg: "请先选择角色" };
    const pos = Number(payload?.pos);
    await (helpers as any).stallService.unshelfAtPos(roleId, pos);
    return { act_id: 1317, code: 0 };
  },

  // 1318：发布摊位（money=0 普通；>0 打包价）
  1318: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId;
    if (!roleId) return { act_id: 1318, code: -1, msg: "请先选择角色" };
    const price = Number(payload?.money || 0);
    await (helpers as any).stallService.publish(roleId, price);
    return { act_id: 1318, code: 0 };
  },

  // 1307：撤销摊位（退回背包）
  1307: async (_payload, helpers) => {
    const roleId = helpers.selectedCharacterId;
    if (!roleId) return { act_id: 1307, code: -1, msg: "请先选择角色" };
    await (helpers as any).stallService.revoke(roleId);
    return { act_id: 1307, code: 0 };
  },

  // 1032：查看他人摊位
  1032: async (payload, helpers) => {
    const stallId = Number(payload?.stallId);
    const data = await (helpers as any).stallService.getStallInfo(stallId);
    return { act_id: 1032, code: 0, data };
  },

  // 1329：购买（单件/打包）
  1329: async (payload, helpers) => {
    const buyerId = helpers.selectedCharacterId || 0;
    const stallId = Number(payload?.stallId);
    const pos = Number(payload?.pos || 0);
    const thingId = Number(payload?.thingId || 0);
    const count = Number(payload?.count || 0);
    const r = await (helpers as any).stallService.buy(buyerId, {
      stallId,
      pos,
      thingId,
      count,
    });
    return { act_id: 1329, code: 0, msg: r.msg };
  },

  // 1312：查看物品详情（简化，返回 basic_items 的描述）
  1312: async (payload, helpers) => {
    const gid = Number(payload?.gid);
    const item = await helpers.basicItemService.getItemById(gid);
    const data = item
      ? [
          { k: "名称:", v: item.name },
          { k: "气血值:", v: `${item.lv * 1250}` },
          { k: "介绍:", v: item.description || "" },
          { k: "等级:", v: String(item.lv || 0) },
        ]
      : [];
    return { act_id: 1312, code: 0, data };
  },

  // 1308：查看我的出售记录
  1308: async (payload, helpers) => {
    const stallId = Number(
      payload?.stallId || helpers.selectedCharacterId || 0
    );
    const list = await (helpers as any).stallService.listTrades(stallId);
    return { act_id: 1308, code: 0, list };
  },

  // 1316：查询我的在架列表（分页）
  1316: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId || 0;
    if (!roleId) return { act_id: 1316, code: -1, msg: "请先选择角色" };
    const pageNum = Number(payload?.pageNum || 0);
    const r = await (helpers as any).stallService.listMyShelf(roleId, pageNum);
    return { act_id: 1316, code: 0, list: r.list, page: r.page, sum: r.sum };
  },

  // 1322：我的出售记录（分页）
  1322: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId || 0;
    if (!roleId) return { act_id: 1322, code: -1, msg: "请先选择角色" };
    const pageNum = Number(payload?.pageNum || 0);
    const r = await (helpers as any).stallService.listMySalesPaged(
      roleId,
      pageNum
    );
    return { act_id: 1322, code: 0, list: r.list, page: r.page, sum: r.sum };
  },

  // 1323：我的购买记录（分页）
  1323: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId || 0;
    if (!roleId) return { act_id: 1323, code: -1, msg: "请先选择角色" };
    const pageNum = Number(payload?.pageNum || 0);
    const r = await (helpers as any).stallService.listMyPurchases(
      roleId,
      pageNum
    );
    return { act_id: 1323, code: 0, list: r.list, page: r.page, sum: r.sum };
  },

  // 1324：我的打包发布记录（占位，当前等同我的出售记录）
  1324: async (payload, helpers) => {
    const roleId = helpers.selectedCharacterId || 0;
    if (!roleId) return { act_id: 1324, code: -1, msg: "请先选择角色" };
    const pageNum = Number(payload?.pageNum || 0);
    const r = await (helpers as any).stallService.listMySalesPaged(
      roleId,
      pageNum
    );
    return { act_id: 1324, code: 0, list: r.list, page: r.page, sum: r.sum };
  },
  // 1075：使用体力丹（gid=82），每日最多4次，每次+50体力，受等级上限限制
  1075: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1075, code: -1, msg: "请先选择角色" };
      }
      const gid = Number(payload?.gid);
      if (!gid) {
        return { act_id: 1075, code: -1, msg: "物品ID无效" };
      }

      const result = await helpers.characterService.useSinewPotion(
        characterId,
        gid
      );
      return { act_id: 1075, code: 0, msg: result.msg };
    } catch (error: any) {
      return { act_id: 1075, code: -1, msg: error?.message || "使用失败" };
    }
  },

  // 1374：在线满30分钟每日体力领取（与等级上限一致），每日一次
  1374: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1374, code: -1, msg: "请先选择角色" };
      }

      const minutes =
        await helpers.playerOnlineTimeService.getTodayOnlineMinutes(
          characterId
        );
      if (minutes < 30) {
        return { act_id: 1374, code: -1, msg: "在线不足30分钟，无法领取" };
      }

      const result = await helpers.characterService.claimDailySinew(
        characterId
      );
      return { act_id: 1374, code: 0, msg: result.msg };
    } catch (error: any) {
      return { act_id: 1374, code: -1, msg: error?.message || "领取失败" };
    }
  },
  // 角色管理模块
  // 3：加载角色数据（来源：game/Login/RoleManageView.js）
  3: async (payload, helpers) => {
    try {
      // 调用CharacterService获取用户的所有角色
      const characters = await helpers.characterService.getUserCharacters(
        helpers.userId
      );

      // 转换为客户端期望的数据格式
      const roleList = characters.map((char: any) => ({
        allowLogin: char.allowLogin || 1,
        headImg: char.headImg || "",
        id: char.id,
        lvl: char.lvl || 1,
        name: char.name || "",
        roleType: char.roleType || 1,
        sex: char.sex || 1,
      }));

      // 生成会话ID（可以使用用户ID和时间戳生成）
      const sid = `1BvXQD_VTPQFVCMxFu0wuE5744823673`; // 这里应该根据实际需求生成

      // 返回客户端期望的完整格式
      return {
        act_id: 3,
        roleCount: roleList.length,
        roleList: roleList,
        sid: sid,
      };
    } catch (error) {
      console.error("获取角色数据失败:", error);
      return {
        act_id: 3,
        code: -1,
        msg: "获取角色数据失败",
        roleCount: 0,
        roleList: [],
        sid: "",
      };
    }
  },

  // 4：角色选择（新增）
  4: async (payload, helpers) => {
    try {
      const { characterId } = payload;

      if (!characterId) {
        return { act_id: 4, code: -1, msg: "角色ID不能为空" };
      }

      // 验证角色是否属于当前用户
      const characters = await helpers.characterService.getUserCharacters(
        helpers.userId
      );
      const character = characters.find((c: any) => c.id === characterId);

      if (!character) {
        return { act_id: 4, code: -1, msg: "角色不存在或不属于当前用户" };
      }

      // 检查角色是否允许登录
      if (character.allowLogin !== 1) {
        return { act_id: 4, code: -1, msg: "该角色不允许登录" };
      }

      // 更新选中的角色
      await helpers.updateSelectedCharacter(characterId, character.name);

      // 在Redis中缓存用户角色选择状态
      await helpers.redisService.set(
        `user:selected_character:${helpers.userId}`,
        JSON.stringify({
          characterId: characterId,
          updated_at: Date.now(),
        }),
        86400 // 24小时过期
      );

      // 返回角色选择成功响应
      return {
        act_id: 4,
        code: 0,
        msg: "角色选择成功",
        data: {
          id: character.id,
          name: character.name,
          roleType: character.roleType,
          sex: character.sex,
          lvl: character.lvl,
          headImg: character.headImg || "",
        },
      };
    } catch (error: any) {
      console.error("角色选择失败:", error);
      return {
        act_id: 4,
        code: -1,
        msg: error.message || "角色选择失败",
      };
    }
  },

  // 5：角色创建或选择（根据请求体内容判断）
  5: async (payload, helpers) => {
    try {
      // 判断是创建角色还是选择角色
      if (payload.roleId) {
        // 选择角色
        const { roleId } = payload;

        if (!roleId) {
          return { act_id: 5, code: -1, msg: "角色ID不能为空" };
        }

        // 验证角色是否属于当前用户
        const characters = await helpers.characterService.getUserCharacters(
          helpers.userId
        );
        const character = characters.find((c: any) => c.id === roleId);

        if (!character) {
          return { act_id: 5, code: -1, msg: "角色不存在或不属于当前用户" };
        }

        // 检查角色是否允许登录
        if (character.allowLogin !== 1) {
          return { act_id: 5, code: -1, msg: "该角色不允许登录" };
        }

        // 更新选中的角色
        await helpers.updateSelectedCharacter(roleId, character.name);

        // 在Redis中缓存用户角色选择状态
        await helpers.redisService.set(
          `user:selected_character:${helpers.userId}`,
          JSON.stringify({
            characterId: roleId,
            roleName: character.name,
            updated_at: Date.now(),
          }),
          86400 // 24小时过期
        );

        // 更新位置服务中的角色信息缓存（确保717指令返回正确的等级）
        if (helpers.locationService) {
          await helpers.locationService.updatePlayerCharacterInfo(roleId);
        }

        // 返回角色选择成功信息
        return {
          act_id: 5,
          code: 0,
          data: {
            id: character.id,
            name: character.name,
            roleType: character.roleType,
            sex: character.sex,
            lvl: character.lvl,
            exp: character.exp,
            trans: character.trans,
            title: character.title || "",
            vip: character.vip || 0,
            headImg: character.headImg || "",
            allowLogin: character.allowLogin,
            objType: character.objType,
            indexID: character.indexID,
          },
          msg: "角色选择成功",
        };
      } else {
        // 创建角色
        const { sex, roleType, headIndex, name } = payload;

        if (
          sex === undefined ||
          sex === null ||
          roleType === undefined ||
          roleType === null
        ) {
          return { act_id: 5, code: -1, msg: "参数不完整" };
        }

        // 验证性别范围 (0:女, 1:男)
        if (sex !== 0 && sex !== 1) {
          return { act_id: 5, code: -1, msg: "性别值无效" };
        }

        // 验证职业类型范围 (1:武士, 2:文人, 3:异师)
        if (roleType < 1 || roleType > 3) {
          return { act_id: 5, code: -1, msg: "职业类型无效" };
        }

        // 角色数量上限校验：最多允许创建3个角色
        try {
          const existingRoles =
            await helpers.characterService.getUserCharacters(helpers.userId);
          if (Array.isArray(existingRoles) && existingRoles.length >= 3) {
            return {
              act_id: 5,
              code: -1,
              msg: "角色数量已达上限(3)，无法创建新角色",
            };
          }
        } catch (e: any) {
          // 查询失败时，不影响后续逻辑，但记录告警
          console.warn(
            `查询用户现有角色失败(userId=${helpers.userId}): ${e?.message || e}`
          );
        }

        // 调用CharacterService创建新角色
        const newCharacter = await helpers.characterService.createNewRole(
          helpers.userId,
          {
            sex,
            roleType,
            headIndex: headIndex || 2,
            name,
          }
        );

        // 角色创建成功后，自动发送大区欢迎消息
        try {
          await helpers.chatMessageService.sendMessage({
            content: "小弟初入江湖请各位大侠多多关照",
            senderName: newCharacter.name,
            senderCharacterId: newCharacter.id,
            messageType: 1, // 大区消息
            areaId: 1, // 默认大区
          });
        } catch (messageError) {
          console.warn(
            `角色创建后发送欢迎消息失败: ${
              messageError instanceof Error
                ? messageError.message
                : String(messageError)
            }`
          );
          // 不抛出错误，因为角色创建已经成功
        }

        return {
          act_id: 5,
          code: 0,
          data: {
            id: newCharacter.id,
            name: newCharacter.name,
            roleType: newCharacter.roleType,
            sex: newCharacter.sex,
            lvl: newCharacter.lvl,
            exp: newCharacter.exp,
            trans: newCharacter.trans,
            title: newCharacter.title || "",
            vip: newCharacter.vip || 0,
            headImg: newCharacter.headImg || `head_${headIndex || 2}`,
            allowLogin: newCharacter.allowLogin,
            objType: newCharacter.objType,
            indexID: newCharacter.indexID,
            headIndex: headIndex || 2,
          },
        };
      }
    } catch (error: any) {
      console.error("角色操作失败:", error);
      return {
        act_id: 5,
        code: -1,
        msg: error.message || "角色操作失败",
      };
    }
  },

  // 390：创建角色（标准指令）
  390: async (payload, helpers) => {
    try {
      const { sex, roleType, headIndex } = payload;

      if (!sex || !roleType) {
        return { act_id: 390, code: -1, msg: "参数不完整" };
      }

      // 验证性别范围 (0:女, 1:男)
      if (sex !== 0 && sex !== 1) {
        return { act_id: 390, code: -1, msg: "性别值无效" };
      }

      // 验证职业类型范围 (1:武士, 2:文人, 3:异师)
      if (roleType < 1 || roleType > 3) {
        return { act_id: 390, code: -1, msg: "职业类型无效" };
      }

      // 调用CharacterService创建新角色
      const newCharacter = await helpers.characterService.createNewRole(
        helpers.userId,
        {
          sex,
          roleType,
          headIndex: headIndex || 2,
          name: `三国新人`, // 默认三国新人
        }
      );

      // 角色创建成功后，自动发送大区欢迎消息
      try {
        await helpers.chatMessageService.sendMessage({
          content: "小弟初入江湖请各位大侠多多关照",
          senderName: newCharacter.name,
          senderCharacterId: newCharacter.id,
          messageType: 1, // 大区消息
          areaId: 1, // 默认大区
        });
      } catch (messageError) {
        console.warn(
          `角色创建后发送欢迎消息失败: ${
            messageError instanceof Error
              ? messageError.message
              : String(messageError)
          }`
        );
        // 不抛出错误，因为角色创建已经成功
      }

      // 返回标准格式：{"act_id":390,"code":0,"data":角色ID}
      return {
        act_id: 390,
        code: 0,
        data: newCharacter.id,
      };
    } catch (error: any) {
      console.error("角色创建失败:", error);
      return {
        act_id: 390,
        code: -1,
        msg: error.message || "角色创建失败",
      };
    }
  },

  // 1000：获取角色信息（来源：game/UserInfoController/UserInfoView.js）
  1000: async (payload, helpers) => {
    try {
      // 从helpers获取当前选中的角色ID
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return { act_id: 1000, code: -1, msg: "请先选择角色", data: null };
      }

      // 使用公共方法获取角色基础属性信息
      const basicAttributes =
        await helpers.characterAttributeService.getCharacterBasicAttributes(
          characterId
        );

      // 获取玩家上阵坐骑信息
      let horseInfo = null;
      try {
        const mountService = helpers.characterMountService;
        if (mountService) {
          const activeMountResult = await mountService.getActiveMountInfo(
            characterId
          );
          if (activeMountResult.success && activeMountResult.data) {
            horseInfo = {
              id: activeMountResult.data.id,
              name: activeMountResult.data.name,
            };
          }
        }
      } catch (error: any) {
        console.warn("获取坐骑信息失败:", error?.message || error);
      }

      // 获取教派信息
      let religionInfo = null;
      try {
        const religion = await helpers.characterService.getCharacterReligion(
          characterId
        );
        if (religion) {
          religionInfo = {
            id: religion.id,
            name: religion.name,
          };
        }
      } catch (error: any) {
        console.warn("获取教派信息失败:", error?.message || error);
      }

      // 获取配偶信息
      let spouseInfo = null;
      try {
        const spouse = await helpers.characterService.getCharacterSpouse(
          characterId
        );
        if (spouse) {
          spouseInfo = {
            id: spouse.id,
            name: spouse.name,
          };
        }
      } catch (error: any) {
        console.warn("获取配偶信息失败:", error?.message || error);
      }

      // 获取师父信息
      let masterInfo = null;
      try {
        const master = await helpers.characterService.getCharacterMaster(
          characterId
        );
        if (master) {
          masterInfo = {
            id: master.id,
            name: master.name,
          };
        }
      } catch (error: any) {
        console.warn("获取师父信息失败:", error?.message || error);
      }

      // 查询角色已装备的天赋石（state=2）填充 stoneList
      let stoneList: any[] = [];
      try {
        // helpers 中未显式声明类型，这里用可选链防御
        const tss: any = (helpers as any).talentStoneService;
        if (tss && typeof tss.getCharacterEquippedStones === "function") {
          stoneList = await tss.getCharacterEquippedStones(characterId);
        }
      } catch {}

      // 返回完整的角色信息
      return {
        act_id: 1000,
        code: 0,
        data: {
          ...basicAttributes,
          // 覆盖 vip 字段：从 vip_status 中读取
          vip: await (async () => {
            try {
              const info = await (helpers as any).vipService?.queryVipInfo(
                characterId,
                -2
              );
              return info?.vipLvl ?? -1;
            } catch {
              return -1;
            }
          })(),
          // 社交关系（使用真实数据）
          religion: religionInfo || { id: 0, name: "无" },
          spouse: spouseInfo || { id: 0, name: "无" },
          master: masterInfo || { id: 0, name: "无" },
          // 居住/房产信息（真实）
          ...(await (async () => {
            try {
              const house = await helpers.characterService.getCharacterHouse(
                characterId
              );
              if (house && typeof house.lvl !== "undefined") {
                const areaName =
                  await helpers.characterService.getCharacterAreaName(
                    characterId
                  );
                return {
                  home: { name: areaName },
                  house: { name: house.n, lvl: house.lvl, remain: house.r },
                };
              }
            } catch {}
            const areaName =
              await helpers.characterService.getCharacterAreaName(characterId);
            return {
              home: { name: areaName },
              house: { name: "未购房", lvl: 0 },
            };
          })()),
          horse: horseInfo, // 玩家上阵坐骑信息
          // 技能信息（使用默认值）
          skill_1: 0,
          skill_2: 0,
          skill_3: 0,
          skill_4: 0,
          // 魂蛋列表（真实查询）
          stoneList,
        },
      };
    } catch (error) {
      console.error("获取角色信息失败:", error);
      return {
        act_id: 1000,
        code: -1,
        msg: "获取角色信息失败",
        data: null,
      };
    }
  },

  // 1001：获取称号列表（来源：game/UserInfoController/UserInfoView.js）
  1001: async () => {
    return {
      code: 0,
      data: [
        { id: 1, name: "新手", description: "初出茅庐的新手" },
        { id: 2, name: "勇士", description: "勇敢的战士" },
        { id: 3, name: "英雄", description: "受人尊敬的英雄" },
        { id: 4, name: "传奇", description: "传说中的强者" },
      ],
    };
  },

  // 1003：修改角色名称（来源：game/UserInfoController/AXModifyNameDialog.js）
  1003: async (payload, helpers) => {
    try {
      const { name } = payload;

      if (!name || name.includes(" ")) {
        return { act_id: 1003, code: -1, msg: "用户名输入不能包含空格" };
      }

      // 从helpers获取当前选中的角色ID（来自token认证）
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return { act_id: 1003, code: -1, msg: "请先选择角色" };
      }

      // 调用CharacterService修改名称（需要消耗改名卡）
      const result = await helpers.characterService.modifyCharacterNameWithCard(
        characterId,
        name
      );

      return {
        act_id: 1003,
        code: 0,
        msg: "改名成功",
        data: { name: result.newName },
      };
    } catch (error: any) {
      console.error("修改角色名称失败:", error);
      return {
        act_id: 1003,
        code: -1,
        msg: error?.message || "修改角色名称失败",
      };
    }
  },

  // 1105：分配副将未分配属性点
  1105: async (payload, helpers) => {
    try {
      const { id, ap = 0, hp = 0, mp = 0, sp = 0 } = payload || {};
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return { act_id: 1105, code: -1, msg: "请先选择角色" };
      }
      if (!id) {
        return { act_id: 1105, code: -1, msg: "副将ID不能为空" };
      }

      // 校验副将归属（通过服务）
      const belongs =
        await helpers.deputyGeneralService.playerDeputyRepository?.findOne({
          where: { deputy_id: id, player_id: characterId },
        });
      if (!belongs) {
        return { act_id: 1105, code: -1, msg: "副将不属于当前玩家" };
      }

      if (!helpers.deputyAttributeService) {
        return { act_id: 1105, code: -1, msg: "服务未就绪" };
      }

      await helpers.deputyAttributeService.allocatePoints(
        id,
        Number(ap) || 0,
        Number(hp) || 0,
        Number(mp) || 0,
        Number(sp) || 0
      );

      return { act_id: 1105, code: 0, msg: "ok", data: null };
    } catch (error: any) {
      return { act_id: 1105, code: -1, msg: error?.message || "分配失败" };
    }
  },

  // 1908：使用改名卡改名（来源：game/UserInfoController/AXChangeNewNameDialog.js）
  // 前端标准：成功时 data 为用于拼接提示的字符串（例如：" 修改成功"），
  // 前端会执行 ToastView.toastView(inputName + e.data)
  1908: async (payload, helpers) => {
    try {
      const { name } = payload || {};

      if (!name || typeof name !== "string") {
        return { act_id: 1908, code: -1, msg: "用户名不能为空" };
      }

      if (name.includes(" ")) {
        return { act_id: 1908, code: -1, msg: "用户名输入不能包含空格" };
      }

      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1908, code: -1, msg: "请先选择角色" };
      }

      // 复用统一改名逻辑（含改名卡消耗与首次免费逻辑）
      await helpers.characterService.modifyCharacterNameWithCard(
        characterId,
        name
      );

      // 按 test-www 标准，成功时 data 为字符串，供前端拼接显示
      return {
        act_id: 1908,
        code: 0,
        msg: "改名成功",
        data: " 修改成功",
      };
    } catch (error: any) {
      return {
        act_id: 1908,
        code: -1,
        msg: error?.message || "修改角色名称失败",
      };
    }
  },

  // 1006：获取当前角色抗性（人物 + 装备 + 宝石）
  1006: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1006, code: -1, msg: "请先选择角色", data: null };
      }

      const data =
        await helpers.characterAttributeService.calculateAggregatedResistances(
          characterId
        );

      return { act_id: 1006, code: 0, data };
    } catch (error) {
      console.error("计算角色抗性失败:", error);
      return { act_id: 1006, code: -1, msg: "计算抗性失败", data: null };
    }
  },

  // 10011：修改称号（来源：game/UserInfoController/UserInfoView.js）
  10011: async (payload, helpers) => {
    try {
      const { titleId, type, characterId } = payload;

      if (!characterId) {
        return { code: -1, msg: "角色ID不能为空" };
      }

      if (type === 1) {
        // 设置称号
        const titles = [
          { id: 1, name: "新手" },
          { id: 2, name: "勇士" },
          { id: 3, name: "英雄" },
          { id: 4, name: "传奇" },
        ];
        const title = titles.find((t) => t.id === parseInt(titleId));

        if (!title) {
          return { code: -1, msg: "称号不存在" };
        }

        // 调用CharacterService更新称号
        await helpers.characterService.updateCharacterTitle(
          characterId,
          title.name
        );

        return {
          code: 0,
          data: { title: title.name },
        };
      } else {
        // 移除称号
        await helpers.characterService.updateCharacterTitle(characterId, "");

        return {
          code: 0,
          data: { title: "" },
        };
      }
    } catch (error) {
      console.error("修改称号失败:", error);
      return {
        code: -1,
        msg: "修改称号失败",
      };
    }
  },

  // 1132：查询当前角色是否开启体力值
  1132: async (payload, helpers) => {
    try {
      if (!helpers.selectedCharacterId) {
        return { act_id: 1132, code: -1, msg: "请先选择角色" };
      }

      // 获取角色资源信息，检查体力值是否开启
      const resources = await helpers.characterService.getCharacterResources(
        helpers.selectedCharacterId
      );

      // 体力值开启状态：如果体力值上限大于0，则认为已开启
      const fight = resources && resources.tlzs > 0;

      return {
        act_id: 1132,
        code: 0,
        data: { fight },
      };
    } catch (error: any) {
      console.error("查询体力值状态失败:", error);
      return {
        act_id: 1132,
        code: -1,
        msg: error.message || "查询失败",
        data: { fight: false },
      };
    }
  },

  // 1382：获取技能列表
  1382: async (payload, helpers) => {
    try {
      if (!helpers.selectedCharacterId) {
        return { act_id: 1382, code: -1, msg: "请先选择角色" };
      }

      // 使用characterSkillService获取技能列表
      const skills = await helpers.characterSkillService.getCharacterSkills(
        helpers.selectedCharacterId
      );

      // 转换为客户端期望的格式
      const skillList = skills.map((skill: any) => ({
        id: skill.skillId,
        name: skill.skillName,
        grade: skill.grade,
        hua: skill.hua,
        useCount: skill.useCount,
        type: skill.skillType,
        side: skill.skillSide,
        short: skill.skillShort,
        ani: skill.skillAni,
        status: skill.status,
      }));

      return {
        act_id: 1382,
        code: 0,
        data: skillList,
      };
    } catch (error: any) {
      console.error("获取技能列表失败:", error);
      return {
        act_id: 1382,
        code: -1,
        msg: error.message || "获取失败",
        data: [],
      };
    }
  },

  // 1409：查询可学习技能的副将列表
  1409: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1409, code: -1, msg: "请先选择角色" };
      const list = await helpers.characterService.getDeputiesForSkillLearn(
        characterId,
        payload?.pageNum ?? 0
      );
      return { act_id: 1409, code: 0, data: list };
    } catch (error: any) {
      return { act_id: 1409, code: -1, msg: error?.message || "查询失败" };
    }
  },

  // 1392：技能升级（角色或副将）
  1392: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1392, code: -1, msg: "请先选择角色" };
      const { id: skillId } = payload || {};
      if (!skillId) return { act_id: 1392, code: 8, msg: "参数不完整" };

      // 角色技能路径：存在于 character_skills
      const skill = await helpers.characterSkillService.getCharacterSkill(
        characterId,
        Number(skillId)
      );
      if (skill) {
        // 等级门槛判断（角色等级）
        try {
          const role = await helpers.characterService.getCharacterById(
            characterId
          );
          const lvl = Number(role?.lvl || 1);
          const nextGrade = Number(skill.grade || 0) + 1;
          const gradeAllowed = (lv: number): number => {
            if (lv >= 70) return 5;
            if (lv >= 50) return 4;
            if (lv >= 30) return 3;
            return 2;
          };
          const maxGrade = gradeAllowed(lvl);
          if (nextGrade > maxGrade) {
            return {
              act_id: 1392,
              code: 8,
              msg: `等级不足，无法升至 ${nextGrade} 级技能`,
            };
          }
        } catch {}

        const need =
          await helpers.characterSkillService.getRequiredProficiencyForUpgradeAsync(
            skill.skillName,
            Number(skill.grade || 0)
          );
        if (Number(skill.useCount || 0) < need)
          return {
            act_id: 1392,
            code: 8,
            msg: `您的熟练度没有到 ${need} 无法升级!`,
          };
        await helpers.characterSkillService.upgradeSkill(
          characterId,
          skill.skillId
        );
        return { act_id: 1392, code: 0 };
      }

      // 否则视为副将技能升级由 1132 流程
      return { act_id: 1392, code: 8, msg: "请选择正确的技能目标" };
    } catch (error: any) {
      return { act_id: 1392, code: -1, msg: error?.message || "升级失败" };
    }
  },

  // 2020：查询可用此技能书的目标（含自身-9 与副将）
  2020: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 2020, code: -1, msg: "请先选择角色" };
      const { gid, pageNum = 0 } = payload || {};
      if (!gid) return { act_id: 2020, code: 8, msg: "参数不完整" };
      const list = await helpers.characterService.getSkillBookTargets(
        characterId,
        Number(gid),
        pageNum
      );
      return { act_id: 2020, code: 0, list, page: 1, sum: list.length };
    } catch (error: any) {
      return {
        act_id: 2020,
        code: -1,
        msg: error?.message || "查询失败",
        list: [],
        page: 1,
        sum: 0,
      };
    }
  },

  // 2021：查询目标可用此技能书的技能
  2021: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 2021, code: -1, msg: "请先选择角色" };
      const { gid, cid, pageNum = 0 } = payload || {};
      if (!gid || typeof cid === "undefined")
        return { act_id: 2021, code: 8, msg: "参数不完整" };
      const list = await helpers.characterService.getSkillsForBook(
        characterId,
        Number(gid),
        Number(cid),
        pageNum
      );
      return { act_id: 2021, code: 0, list };
    } catch (error: any) {
      return {
        act_id: 2021,
        code: -1,
        msg: error?.message || "查询失败",
        list: [],
      };
    }
  },

  // 2022：使用技能书（消耗道具，增加熟练度）
  2022: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 2022, code: -1, msg: "请先选择角色" };
      const { gid, cid, sid, c = 1 } = payload || {};
      if (!gid || typeof cid === "undefined" || !sid)
        return { act_id: 2022, code: 8, msg: "参数不完整" };
      const msg = await helpers.characterService.useSkillBook(
        characterId,
        Number(gid),
        Number(cid),
        Number(sid),
        Number(c)
      );
      return { act_id: 2022, code: 0, data: msg };
    } catch (error: any) {
      return { act_id: 2022, code: -1, msg: error?.message || "使用失败" };
    }
  },

  // 210：查询药品信息
  210: async (payload, helpers) => {
    try {
      const { no = 1 } = payload;

      // 返回药品列表信息
      const medicineList = [
        {
          act_id: 1241,
          content: "免费治疗",
          is_NewLine: 1,
          p1: 9,
          type: 53,
        },
        {
          act_id: 1242,
          content: "跌打药(血)",
          is_NewLine: 1,
          p1: 1,
          p2: 1,
          p3: 1,
          type: 76,
        },
        { content: " ", is_NewLine: 2, type: 10 },
        {
          act_id: 1243,
          content: "购买",
          is_NewLine: 0,
          p1: 1,
          p2: 1,
          p3: 1,
          type: 57,
        },
        {
          act_id: 1242,
          content: "止血药(血)",
          is_NewLine: 1,
          p1: 2,
          p2: 1,
          p3: 1,
          type: 76,
        },
        { content: " ", is_NewLine: 2, type: 10 },
        {
          act_id: 1243,
          content: "购买",
          is_NewLine: 0,
          p1: 2,
          p2: 1,
          p3: 1,
          type: 57,
        },
        {
          act_id: 1242,
          content: "金创药(血)",
          is_NewLine: 1,
          p1: 3,
          p2: 1,
          p3: 1,
          type: 76,
        },
        { content: " ", is_NewLine: 2, type: 10 },
        {
          act_id: 1243,
          content: "购买",
          is_NewLine: 0,
          p1: 3,
          p2: 1,
          p3: 1,
          type: 57,
        },
        {
          act_id: 1242,
          content: "回春汤(精)",
          is_NewLine: 1,
          p1: 17,
          p2: 2,
          p3: 1,
          type: 76,
        },
        { content: " ", is_NewLine: 2, type: 10 },
        {
          act_id: 1243,
          content: "购买",
          is_NewLine: 0,
          p1: 17,
          p2: 2,
          p3: 1,
          type: 57,
        },
        {
          act_id: 1242,
          content: "花蜜酒(精)",
          is_NewLine: 1,
          p1: 18,
          p2: 2,
          p3: 1,
          type: 76,
        },
        { content: " ", is_NewLine: 2, type: 10 },
        {
          act_id: 1243,
          content: "购买",
          is_NewLine: 0,
          p1: 18,
          p2: 2,
          p3: 1,
          type: 57,
        },
        {
          act_id: 1242,
          content: "清泉酒(精)",
          is_NewLine: 1,
          p1: 19,
          p2: 2,
          p3: 1,
          type: 76,
        },
        { content: " ", is_NewLine: 2, type: 10 },
        {
          act_id: 1243,
          content: "购买",
          is_NewLine: 0,
          p1: 19,
          p2: 2,
          p3: 1,
          type: 57,
        },
        { content: "", is_NewLine: 1, type: 99 },
        {
          act_id: 1245,
          content: "药品回收",
          is_NewLine: 1,
          type: 57,
        },
      ];

      return {
        act_id: 600, // 药品查询返回的act_id
        imgPath: "",
        list: medicineList,
        page_id: 0,
        page_style: 8,
        page_type: 0,
        rtn_act_id: 0,
      };
    } catch (error: any) {
      console.error("查询药品信息失败:", error);
      return {
        act_id: 600,
        code: -1,
        msg: error.message || "查询失败",
        list: [],
      };
    }
  },

  // 1450：查询钱庄金币信息
  1450: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;

      if (!helpers.selectedCharacterId) {
        return { act_id: 1450, code: -1, msg: "请先选择角色" };
      }

      // 获取角色资源信息
      const resources = await helpers.characterService.getCharacterResources(
        helpers.selectedCharacterId
      );

      return {
        act_id: 1450,
        code: 0,
        data: {
          balanceGold: resources?.balanceGold || 0,
          balanceMoney: resources?.balanceMoney || 0,
          gold: resources?.gold || 0,
          money: resources?.silver || 0,
        },
      };
    } catch (error: any) {
      console.error("查询钱庄信息失败:", error);
      return {
        act_id: 1450,
        code: -1,
        msg: error.message || "查询失败",
        data: {
          balanceGold: 0,
          balanceMoney: 0,
          gold: 0,
          money: 0,
        },
      };
    }
  },

  // 1455：查询金币市场交易信息（聚合前5档）
  1455: async (payload, helpers) => {
    try {
      const levels = await (helpers as any).goldTradeService.getTopLevels();
      const sum =
        levels
          .filter((l: any) => l.type === 2)
          .map((l: any) => l.price)
          .sort((a: number, b: number) => a - b)[0] || 0;
      return { act_id: 1455, code: 0, list: levels, sum };
    } catch (error: any) {
      return {
        act_id: 1455,
        code: -1,
        msg: error?.message || "查询失败",
        list: [],
        sum: 0,
      };
    }
  },

  // 1457：银币从银行取出
  1457: async (payload, helpers) => {
    try {
      const { num, pwd } = payload;

      if (!helpers.selectedCharacterId) {
        return { act_id: 1457, code: -1, msg: "请先选择角色" };
      }

      if (!num || num <= 0) {
        return { act_id: 1457, code: 8, msg: "取款数额不正确,请重新输入" };
      }

      if (!pwd) {
        return { act_id: 1457, code: -1, msg: "请输入密码" };
      }

      // 调用银行服务取出银币
      const result = await helpers.bankService.withdrawSilver(
        helpers.selectedCharacterId,
        num,
        pwd
      );

      // 操作成功后，主动触发1450请求查询最新余额并推送给用户
      try {
        const balanceData =
          await helpers.characterService.getCharacterResources(
            helpers.selectedCharacterId
          );

        // 构造1450响应数据
        const balanceResponse = {
          act_id: 1450,
          code: 0,
          data: {
            balanceGold: balanceData?.balanceGold || 0,
            balanceMoney: balanceData?.balanceMoney || 0,
            gold: balanceData?.gold || 0,
            money: balanceData?.silver || 0,
          },
        };

        helpers.pushMessage(balanceResponse);
      } catch (balanceError) {
        console.error("推送余额更新失败:", balanceError);
      }

      return {
        act_id: 1457,
        code: 0,
        msg: "银币取出成功",
        data: result.data,
      };
    } catch (error: any) {
      console.error("银币取出失败:", error);
      return {
        act_id: 1457,
        code: 8,
        msg: error.message || "取款数额不正确,请重新输入",
      };
    }
  },

  // 1459：银币存入银行
  1459: async (payload, helpers) => {
    try {
      const { num } = payload;

      if (!helpers.selectedCharacterId) {
        return { act_id: 1459, code: -1, msg: "请先选择角色" };
      }

      if (!num || num <= 0) {
        return { act_id: 1459, code: 8, msg: "存款数额不正确,请重新输入" };
      }

      // 调用银行服务存入银币
      const result = await helpers.bankService.depositSilver(
        helpers.selectedCharacterId,
        num
      );

      // 操作成功后，主动触发1450请求查询最新余额并推送给用户
      try {
        const balanceData =
          await helpers.characterService.getCharacterResources(
            helpers.selectedCharacterId
          );

        // 构造1450响应数据
        const balanceResponse = {
          act_id: 1450,
          code: 0,
          data: {
            balanceGold: balanceData?.balanceGold || 0,
            balanceMoney: balanceData?.balanceMoney || 0,
            gold: balanceData?.gold || 0,
            money: balanceData?.silver || 0,
          },
        };

        // 通过WebSocket网关推送给用户
        helpers.pushMessage(balanceResponse);
      } catch (balanceError) {
        console.error("推送余额更新失败:", balanceError);
      }

      return {
        act_id: 1459,
        code: 0,
        msg: "银币存入成功",
        data: result.data,
      };
    } catch (error: any) {
      console.error("银币存入失败:", error);
      return {
        act_id: 1459,
        code: 8,
        msg: error.message || "存款数额不正确,请重新输入",
      };
    }
  },

  // 1456：我的交易记录
  1456: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      const pageNum = (payload && payload.pageNum) || 0;
      if (!characterId) return { act_id: 1456, code: -1, msg: "请先选择角色" };
      const list = await (helpers as any).goldTradeService.getMyOrders(
        characterId,
        Number(pageNum)
      );
      return { act_id: 1456, code: 0, list };
    } catch (error: any) {
      return {
        act_id: 1456,
        code: -1,
        msg: error?.message || "查询失败",
        list: [],
      };
    }
  },

  // 1463：下单（求购/出售）
  1463: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1463, code: -1, msg: "请先选择角色" };
      const { type, count, price } = payload || {};
      if (![1, 2].includes(Number(type)) || !Number(count) || !Number(price))
        return { act_id: 1463, code: 8, msg: "价格或数量不合法" };
      const result = await (helpers as any).goldTradeService.placeOrder(
        Number(characterId),
        Number(type) as 1 | 2,
        Number(count),
        Number(price)
      );
      // 交易撮合产生的系统消息：入库并推送
      try {
        const notifications = (result && (result as any).notifications) || [];
        if (Array.isArray(notifications) && notifications.length > 0) {
          for (const n of notifications) {
            const body = {
              content: String(n.content || ""),
              date: String(n.time || ""),
              fname: "系统信息",
            };
            if ((helpers as any).systemMessageService) {
              await (helpers as any).systemMessageService.savePersonalMessage(
                body,
                Number(n.receiverId),
                1000,
                "系统"
              );
            }
            if (helpers.pushPrivateMessageNotification) {
              helpers.pushPrivateMessageNotification(
                Number(n.receiverId),
                1000,
                1
              );
            }
          }
        }
      } catch (_) {}
      return { act_id: 1463, code: 0 };
    } catch (error: any) {
      return { act_id: 1463, code: 8, msg: error?.message || "下单失败" };
    }
  },

  // 1467：撤单（type=1求购,2出售，orderId=订单ID）
  1467: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1467, code: -1, msg: "请先选择角色" };
      const { type, orderId } = payload || {};
      if (![1, 2].includes(Number(type)) || !Number(orderId))
        return { act_id: 1467, code: 8, msg: "参数不合法" };
      await (helpers as any).goldTradeService.cancelOrder(
        Number(characterId),
        Number(type) as 1 | 2,
        Number(orderId)
      );
      return { act_id: 1467, code: 0, msg: "ok", data: null };
    } catch (error: any) {
      return { act_id: 1467, code: 8, msg: error?.message || "撤单失败" };
    }
  },

  // 1460：金币从银行取出
  1460: async (payload, helpers) => {
    try {
      const { num, pwd } = payload;

      if (!helpers.selectedCharacterId) {
        return { act_id: 1460, code: -1, msg: "请先选择角色" };
      }

      if (!num || num <= 0) {
        return { act_id: 1460, code: 8, msg: "取款数额不正确,请重新输入" };
      }

      if (!pwd) {
        return { act_id: 1460, code: -1, msg: "请输入密码" };
      }

      // 调用银行服务取出金币
      const result = await helpers.bankService.withdrawGold(
        helpers.selectedCharacterId,
        num,
        pwd
      );

      // 操作成功后，主动触发1450请求查询最新余额并推送给用户
      try {
        const balanceData =
          await helpers.characterService.getCharacterResources(
            helpers.selectedCharacterId
          );

        // 构造1450响应数据
        const balanceResponse = {
          act_id: 1450,
          code: 0,
          data: {
            balanceGold: balanceData?.balanceGold || 0,
            balanceMoney: balanceData?.balanceMoney || 0,
            gold: balanceData?.gold || 0,
            money: balanceData?.silver || 0,
          },
        };

        // 通过WebSocket网关推送给用户
        helpers.pushMessage(balanceResponse);
      } catch (balanceError) {
        console.error("推送余额更新失败:", balanceError);
      }

      return {
        act_id: 1460,
        code: 0,
        msg: "金币取出成功",
        data: result.data,
      };
    } catch (error: any) {
      console.error("金币取出失败:", error);
      return {
        act_id: 1460,
        code: 8,
        msg: error.message || "取款数额不正确,请重新输入",
      };
    }
  },

  // 1462：金币存入银行
  1462: async (payload, helpers) => {
    try {
      const { num } = payload;

      if (!helpers.selectedCharacterId) {
        return { act_id: 1462, code: -1, msg: "请先选择角色" };
      }

      if (!num || num <= 0) {
        return { act_id: 1462, code: 8, msg: "存款数额不正确,请重新输入" };
      }

      // 调用银行服务存入金币
      const result = await helpers.bankService.depositGold(
        helpers.selectedCharacterId,
        num
      );

      // 操作成功后，主动触发1450请求查询最新余额并推送给用户
      try {
        const balanceData =
          await helpers.characterService.getCharacterResources(
            helpers.selectedCharacterId
          );

        // 构造1450响应数据
        const balanceResponse = {
          act_id: 1450,
          code: 0,
          msg: "金币存入成功",
          data: {
            balanceGold: balanceData?.balanceGold || 0,
            balanceMoney: balanceData?.balanceMoney || 0,
            gold: balanceData?.gold || 0,
            money: balanceData?.silver || 0,
          },
        };

        // 通过WebSocket网关推送给用户
        helpers.pushMessage(balanceResponse);
      } catch (balanceError) {
        console.error("推送余额更新失败:", balanceError);
      }

      return {
        act_id: 1462,
        code: 0,
        msg: "金币存入成功",
        data: result.data,
      };
    } catch (error: any) {
      console.error("金币存入失败:", error);
      return {
        act_id: 1462,
        code: 8,
        msg: error.message || "存款数额不正确,请重新输入",
      };
    }
  },

  // 6102：查询VIP信息
  6102: async (payload, helpers) => {
    try {
      const { lvl = -2 } = payload;

      if (!helpers.selectedCharacterId) {
        return { act_id: 6102, code: -1, msg: "请先选择角色" };
      }

      const data = await (helpers as any).vipService.queryVipInfo(
        helpers.selectedCharacterId,
        Number(lvl)
      );
      return { act_id: 6102, code: 0, data };
    } catch (error: any) {
      console.error("查询VIP信息失败:", error);
      return {
        act_id: 6102,
        code: -1,
        msg: error.message || "查询失败",
        data: {
          hpBag: "无",
          list: [],
          maxLvl: 9,
          next: 1,
          vipLvl: -1,
        },
      };
    }
  },

  // 6103：VIP 可选穿戴列表
  6103: async (payload, helpers) => {
    try {
      const { pid = 1 } = payload || {};
      const list = await (helpers as any).vipService.getVipSelectableWear(
        Number(pid)
      );
      return { act_id: 6103, code: 0, list };
    } catch (error: any) {
      return {
        act_id: 6103,
        code: -1,
        msg: error?.message || "查询失败",
        list: [],
      };
    }
  },

  // 61020：消耗金砖(金币)注入 VIP 经验（1金币=1 VIP 经验）
  61020: async (payload, helpers) => {
    try {
      if (!helpers.selectedCharacterId) {
        return { act_id: 61020, code: -1, msg: "请先选择角色" };
      }
      const amount = Number(payload?.next || 0);
      if (!Number.isFinite(amount) || amount <= 0) {
        return { act_id: 61020, code: -1, msg: "金额不正确" };
      }
      const characterId = helpers.selectedCharacterId;
      const res = await helpers.characterService.getCharacterResources(
        characterId
      );
      const curGold = res?.gold || 0;
      if (curGold < amount) {
        return { act_id: 61020, code: 8, msg: "您携带的金币不足" };
      }
      // 扣减金币
      await helpers.characterService.updateCharacterResources(characterId, {
        gold: -amount,
      });
      // 注入 VIP 经验
      const result = await (helpers as any).vipService.addVipExp(
        characterId,
        amount
      );
      return {
        act_id: 61020,
        code: 0,
        data: result,
      };
    } catch (error: any) {
      return {
        act_id: 61020,
        code: -1,
        msg: error?.message || "处理失败",
      };
    }
  },

  // 6154：领取/应用 VIP 穿戴
  6154: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 6154, code: -1, msg: "请先选择角色" };
      }
      const { pid = 1, npcid = 0 } = payload || {};
      const result = await (helpers as any).vipService.claimVipWear(
        characterId,
        { pid: Number(pid), npcid: Number(npcid) }
      );
      return { act_id: 6154, code: 0, data: result.message };
    } catch (error: any) {
      return {
        act_id: 6154,
        code: -1,
        msg: error?.message || "领取失败",
      };
    }
  },

  // 61021：测试重置VIP等级与经验
  61021: async (_payload, helpers) => {
    try {
      if (!helpers.selectedCharacterId) {
        return { act_id: 61021, code: -1, msg: "请先选择角色" };
      }
      await (helpers as any).vipService.resetVip(helpers.selectedCharacterId);
      return { act_id: 61021, code: 0, data: true };
    } catch (e: any) {
      return { act_id: 61021, code: -1, msg: e?.message || "重置失败" };
    }
  },

  // 5326：查询积分信息
  5326: async (payload, helpers) => {
    try {
      if (!helpers.selectedCharacterId) {
        return { act_id: 5326, code: -1, msg: "请先选择角色" };
      }

      // 返回积分信息，暂时返回0
      return {
        act_id: 5326,
        code: 0,
        data: 0, // 积分数量
      };
    } catch (error: any) {
      console.error("查询积分信息失败:", error);
      return {
        act_id: 5326,
        code: -1,
        msg: error.message || "查询失败",
        data: 0,
      };
    }
  },

  // 320：查看当前玩家上阵副将
  320: async (payload, helpers) => {
    try {
      if (!helpers.selectedCharacterId) {
        return { act_id: 320, code: -1, msg: "请先选择角色" };
      }

      // 调用副将服务获取上阵副将列表
      const result = await helpers.deputyGeneralService.getDeputyList(
        helpers.selectedCharacterId,
        true // deployedOnly = true，只获取上阵的副将
      );

      // 按照标准格式返回上阵副将列表
      const deployedDeputies = result.list.map((deputy: any) => ({
        headImg: deputy.head_img || "", // 使用头像图片字段
        id: deputy.id, // 副将ID
        roleType: deputy.roleType, // 职业类型
        sex: deputy.sex || 0, // 性别，从数据库获取
      }));

      return {
        act_id: 320,
        code: 0,
        list: deployedDeputies,
      };
    } catch (error: any) {
      console.error("查询上阵副将失败:", error);
      return {
        act_id: 320,
        code: -1,
        msg: error.message || "查询失败",
        list: [],
      };
    }
  },

  // 基础/导航
  // 200：进入主界面/初始化（来源：game/AXTabBarItemView.js, common/NpcTaskListView.js）
  200: async () => ({ data: null }),

  // 聊天/私聊模块
  // 1023：发送私聊消息（来源：game/FriendMomentController/PrivateChatDialog.js）
  1023: async (payload, helpers) => {
    try {
      const { content, receiverCharacterId } = payload;

      if (!content || !receiverCharacterId) {
        return {
          act_id: 1023,
          code: -1,
          msg: "消息内容或接收者角色ID不能为空",
        };
      }

      if (!helpers.selectedCharacterId) {
        return { act_id: 1023, code: -1, msg: "请先选择角色" };
      }

      // 发送私信消息
      const message = await helpers.privateMessageService.sendPrivateMessage(
        {
          content,
          senderCharacterId: helpers.selectedCharacterId,
          receiverCharacterId,
          messageType: 1, // 玩家消息
        },
        (receiverCharacterId: number, senderCharacterId: number) => {
          // 推送私信通知给接收者
          if (helpers.pushPrivateMessageNotification) {
            helpers.pushPrivateMessageNotification(
              receiverCharacterId,
              senderCharacterId,
              1 // 1表示玩家消息
            );
          }
        }
      );

      return {
        act_id: 1023,
        code: 0,
        msg: "私信发送成功",
        data: {
          id: message.id,
          content: message.content,
          receiverName: message.receiverName,
        },
      };
    } catch (error: any) {
      console.error("发送私信失败:", error);
      return {
        act_id: 1023,
        code: -1,
        msg: error.message || "发送私信失败",
      };
    }
  },
  // 1033：拉取与某人的聊天记录列表
  1033: async (payload, helpers) => {
    try {
      const { roleid } = payload;

      if (!roleid) {
        return { act_id: 1033, code: -1, msg: "角色ID不能为空" };
      }

      if (!helpers.selectedCharacterId) {
        return { act_id: 1033, code: 0, msg: "请先选择角色" };
      }

      // 判断是系统消息还是私聊消息
      const isSystemMessage = roleid === 1000;

      console.log("isSystemMessage", isSystemMessage);
      if (isSystemMessage) {
        // 系统消息处理 - 从 system_messages 表获取
        const messages = await helpers.systemMessageService.getPersonalMessages(
          helpers.selectedCharacterId,
          20,
          0
        );

        console.log("system messages", messages);

        // 标记消息为已读：批量更新该角色所有系统消息为已读
        await helpers.systemMessageService.markAllPersonalAsRead(
          helpers.selectedCharacterId
        );

        // 转换消息格式以匹配前端期望的标准格式
        const formattedMessages = messages.map((msg: SystemMessageEntity) => {
          try {
            // 解析messageBody字符串为对象
            return typeof msg.messageBody === "string"
              ? JSON.parse(msg.messageBody)
              : msg.messageBody;
          } catch (error) {
            console.error(
              "解析系统消息messageBody失败:",
              error,
              "原始数据:",
              msg.messageBody
            );
            // 如果解析失败，返回默认格式
            return {
              content: msg.messageBody || "消息内容解析失败",
              date: msg.created_at
                ? new Date(msg.created_at).toLocaleTimeString("zh-CN", {
                    hour12: false,
                    hour: "2-digit",
                    minute: "2-digit",
                    second: "2-digit",
                  })
                : "00:00:00",
              fname: msg.senderName || "系统信息",
            };
          }
        });

        return {
          act_id: 1033,
          code: 0,
          list: formattedMessages,
          more: {
            name: "系统消息",
            religion: false,
            roleId: 1000,
          },
        };
      } else {
        // 私聊消息处理 - 从 private_messages 表获取
        const messages =
          await helpers.privateMessageService.getPrivateMessageList(
            helpers.selectedCharacterId,
            roleid,
            20
          );

        // 标记消息为已读：批量更新与对方的所有消息为已读
        await helpers.privateMessageService.markAllAsRead(
          helpers.selectedCharacterId,
          roleid
        );

        // 获取接收者角色信息
        const receiverCharacter =
          await helpers.characterService.getCharacterById(roleid);
        const receiverName = receiverCharacter
          ? receiverCharacter.name
          : `角色${roleid}`;

        return {
          act_id: 1033,
          code: 0,
          list: messages,
          more: {
            name: `与[${receiverName}]私聊`,
            friend: true,
            religion: false,
            roleId: roleid,
          },
        };
      }
    } catch (error: any) {
      console.error("获取私信记录失败:", error);
      return {
        act_id: 1033,
        code: -1,
        msg: error.message || "获取私信记录失败",
        list: [],
        more: {
          name: "私聊",
          friend: false,
          religion: false,
          roleId: 0,
        },
      };
    }
  },

  // 好友/社交
  // 1020：获取某个用户资料
  1020: async (payload, helpers) => {
    try {
      const { userId } = payload;

      if (!userId) {
        return { act_id: 1020, code: -1, msg: "用户ID不能为空", data: null };
      }

      // 调用CharacterService获取玩家完整信息
      const playerData = await helpers.characterService.getPlayerFullInfo(
        userId
      );

      // 动态覆盖 vip 等级为数据库 vip_status
      try {
        const vipInfo = await (helpers as any).vipService?.queryVipInfo(
          userId,
          -2
        );
        if (playerData && vipInfo) {
          (playerData as any).vip = vipInfo.vipLvl ?? -1;
        }
      } catch {}

      if (!playerData) {
        return { act_id: 1020, code: -1, msg: "角色不存在", data: null };
      }

      return {
        act_id: 1020,
        code: 0,
        data: playerData,
      };
    } catch (error: any) {
      console.error("获取用户资料失败:", error);
      return {
        act_id: 1020,
        code: -1,
        msg: error.message || "获取用户资料失败",
        data: null,
      };
    }
  },
  // 1024：添加好友
  1024: async () => ({ data: true }),
  // 1026：好友拉黑/解除拉黑
  1026: async () => ({ data: true }),
  // 1038：删除好友
  1038: async () => ({ data: true }),

  // 区域/地图
  // 1418：选择区域
  1418: async (payload, helpers) => {
    try {
      const { areaId } = payload;

      if (!areaId) {
        return { act_id: 1418, code: -1, msg: "区域ID不能为空" };
      }

      // 获取指定区域的子区域列表
      const subAreas = await helpers.mapAreaService.getSubAreasByParentId(
        areaId
      );

      // 格式化返回数据，包含等级信息
      const list = subAreas.map((area: any) => ({
        id: area.id,
        name: area.extension ? `${area.name}${area.extension}` : area.name,
      }));

      return {
        act_id: 1418,
        code: 0,
        list,
      };
    } catch (error: any) {
      console.error("选择区域失败:", error);
      return {
        act_id: 1418,
        code: -1,
        msg: error.message || "选择区域失败",
        list: [],
      };
    }
  },

  // 1436：获取站点/路径信息
  1436: async (payload, helpers) => {
    try {
      const { pid } = payload;

      if (!pid) {
        return { act_id: 1436, code: -1, msg: "父级区域ID不能为空" };
      }

      // 获取指定父级区域的子区域列表
      const subAreas = await helpers.mapAreaService.getSubAreasByParentId(pid);

      // 格式化返回数据，包含等级信息
      const list = subAreas.map((area: any) => ({
        id: area.id,
        name: area.extension ? `${area.name}${area.extension}` : area.name,
      }));

      return {
        act_id: 1436,
        code: 0,
        list,
      };
    } catch (error: any) {
      console.error("获取站点信息失败:", error);
      return {
        act_id: 1436,
        code: -1,
        msg: error.message || "获取站点信息失败",
        list: [],
      };
    }
  },

  // 1437：前往站点
  1437: async (payload, helpers) => {
    try {
      const { siteId } = payload;

      if (!siteId) {
        return { act_id: 1437, code: 1, message: "目标位置ID不能为空" };
      }

      // 获取当前玩家的角色ID
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return { act_id: 1437, code: 1, message: "无法获取玩家角色ID" };
      }

      // 验证目标位置是否存在
      const targetArea = await helpers.mapAreaService.getAreaById(siteId);
      if (!targetArea) {
        return { act_id: 1437, code: 1, message: `目标位置不存在: ${siteId}` };
      }

      // 调用位置服务更新玩家位置（会自动同步到Redis）
      if (helpers.locationService) {
        await helpers.locationService.updatePlayerLocation(characterId, siteId);
      }

      console.log(
        `✅ 玩家 ${characterId} 已移动到位置 ${siteId} (${targetArea.name})`
      );

      helpers.sendCharacterLocationInfo(characterId);
      return { act_id: 1437, code: 0 };
    } catch (error: any) {
      console.error(`❌ 玩家移动失败:`, error);
      return {
        act_id: 1437,
        code: 1,
        message: `移动失败: ${error.message}`,
      };
    }
  },
  // 1826：副本进入/信息
  1826: async () => ({ data: true }),

  // 聊天消息模块
  // 66：获取登录后的消息列表（区域、商业、帮派、系统）
  66: async (payload, helpers) => {
    // 获取系统消息最近10条
    const systemMessages = await helpers.chatMessageService.getSystemMessages(
      10
    );
    try {
      const messages = await helpers.chatMessageService.getLoginMessages(50);
      return {
        act_id: 66,
        code: 0,
        data: [...messages, ...systemMessages],
      };
    } catch (error) {
      console.error("获取登录消息失败:", error);
      return {
        act_id: 66,
        code: -1,
        msg: "获取消息失败",
        data: [],
      };
    }
  },

  // 公共公告模块
  // 90：获取公告列表（分页）
  90: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;
      const result = await helpers.announcementService.getAnnouncementList(
        pageNum,
        20
      );
      return {
        act_id: 90,
        code: 0,
        list: result.list,
        total: result.total,
        pageNum: result.pageNum,
        pageSize: result.pageSize,
        totalPages: result.totalPages,
      };
    } catch (error) {
      console.error("获取公告列表失败:", error);
      return {
        act_id: 90,
        code: -1,
        msg: "获取公告列表失败",
        list: [],
      };
    }
  },

  // 260：发送消息
  260: async (payload, helpers) => {
    try {
      // 前端发送格式：{"c":260,"d":{"t":x,"c":"消息内容"}}
      const { c: content, t: messageType, areaId = 1, factionId } = payload;

      if (!content || messageType === undefined) {
        return { act_id: 260, code: -1, msg: "消息内容或类型不能为空" };
      }

      // 检查发送间隔限制（10秒）
      const lastMessageTimeKey = `last_message_time:${helpers.selectedCharacterId}`;
      const lastMessageTime = await helpers.redisService.get(
        lastMessageTimeKey
      );

      if (lastMessageTime) {
        const lastTime = parseInt(lastMessageTime);
        const currentTime = Date.now();
        const timeDiff = currentTime - lastTime;
        const cooldownTime = 10 * 1000; // 10秒

        if (timeDiff < cooldownTime) {
          const remainingSeconds = Math.ceil((cooldownTime - timeDiff) / 1000);
          return {
            act_id: 260,
            code: -1,
            msg: `还需要等待${remainingSeconds}秒才能发言`,
          };
        }
      }

      // 验证消息类型 - 只允许发送1(区频道)、4(帮派频道)、5(商屏)消息
      const allowedMessageTypes = [1, 4, 5];
      if (!allowedMessageTypes.includes(messageType)) {
        return {
          act_id: 260,
          code: -1,
          msg: `不支持的消息类型: ${messageType}。只允许发送区频道(1)、帮派频道(4)、商屏(5)消息`,
        };
      }

      // 获取当前角色信息
      const character = await helpers.characterService.getCharacterById(
        helpers.selectedCharacterId
      );
      if (!character) {
        return { act_id: 260, code: -1, msg: "角色不存在" };
      }

      // 检查角色名称是否已修改（防止发送大区消息时的错误）
      if (messageType === 1 && character.name === "三国新人") {
        return { act_id: 260, code: 8, msg: "请修改名称后才可以再来此发言！" };
      }

      // 验证消息内容长度
      if (content.length > 500) {
        return {
          act_id: 260,
          code: -1,
          msg: "消息内容过长，不能超过500个字符",
        };
      }

      // 发送消息
      const message = await helpers.chatMessageService.sendMessage({
        content,
        senderName: character.name,
        senderCharacterId: character.id,
        messageType,
        areaId: messageType === 1 ? areaId : undefined,
        factionId: messageType === 4 ? factionId : undefined,
      });

      // 更新最后发送时间到Redis
      const currentTime = Date.now();
      await helpers.redisService.set(
        lastMessageTimeKey,
        currentTime.toString(),
        60
      ); // 60秒过期

      // 使用统一的发布方法广播消息
      try {
        // {"c":"谁压的","h":"10:44","id":41015,"n":"光顾","rid":2093,"t":1}
        const broadcastMessage = {
          act_id: 260,
          code: 0,
          msg: content,
          data: message,
        };

        // 直接通过redisService发布消息到相应频道
        if (messageType === 1 && areaId) {
          // 区频道消息：发布到区服频道
          await helpers.redisService.publish(
            `area:${areaId}`,
            JSON.stringify(broadcastMessage)
          );
          console.log(`✅ 区频道消息已发布到Redis频道 area:${areaId}`);
        } else if (messageType === 4 && factionId) {
          // 帮派频道消息：发布到帮派频道
          await helpers.redisService.publish(
            `faction:${factionId}`,
            JSON.stringify(broadcastMessage)
          );
          console.log(`✅ 帮派频道消息已发布到Redis频道 faction:${factionId}`);
        } else if (messageType === 5) {
          // 商屏消息：发布到全服频道
          await helpers.redisService.publish(
            "global",
            JSON.stringify(broadcastMessage)
          );
          console.log(`✅ 商屏消息已发布到Redis全服频道`);
        } else {
          console.log(
            `✅ 消息发送成功，但未发布广播 (messageType: ${messageType})`
          );
        }
      } catch (broadcastError: any) {
        console.error(
          "广播消息失败:",
          broadcastError?.message || broadcastError
        );
        // 广播失败不影响消息发送的成功返回
      }

      return {
        act_id: 260,
        code: 0,
        msg: content, // 返回发送的消息内容
      };
    } catch (error: any) {
      console.error("发送消息失败:", error);
      return {
        act_id: 260,
        code: -1,
        msg: error.message || "发送消息失败",
      };
    }
  },

  // 1068：丢弃背包物品指令
  1068: async (payload, helpers) => {
    try {
      const { gid, count = 1 } = payload;

      // 验证参数
      if (!gid || typeof gid !== "number") {
        return {
          act_id: 1068,
          code: -1,
          msg: "物品ID不能为空且必须为数字",
        };
      }

      if (count <= 0 || !Number.isInteger(count)) {
        return {
          act_id: 1068,
          code: -1,
          msg: "丢弃数量必须为正整数",
        };
      }

      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return {
          act_id: 1068,
          code: -1,
          msg: "请先选择角色",
        };
      }

      // 自动判断矿石背包/杂物背包丢弃
      const result = await helpers.inventoryService.discardItemAuto(
        characterId,
        gid,
        count
      );

      if (result.success) {
        return {
          act_id: 1068,
          code: 0,
          msg: result.message,
        };
      } else {
        return {
          act_id: 1068,
          code: -1,
          msg: result.message,
        };
      }
    } catch (error: any) {
      console.error("处理丢弃背包物品指令1068失败:", error);
      return {
        act_id: 1068,
        code: -1,
        msg: error?.message || "丢弃物品失败",
      };
    }
  },

  // 帮派/派系相关指令已移至 faction-ws-handlers.ts
  // 1196：帮派详情
  1196: async () => ({ data: null }),
  // 1210：帮派排行榜（支持 type, pageNum）
  1210: async () => ({ list: [], total: 0, pageNum: 0 }),

  // 排行榜
  // 1192：玩家/副将排行榜
  1192: async (payload, helpers) => {
    try {
      const { type = 1, pageNum = 0, myrate = 0 } = payload;
      const pageSize = 50; // 每页显示50条
      const offset = pageNum * pageSize;

      let list: any[] = [];
      let total = 0;
      let more = "";

      if (type === 1) {
        // 玩家高手榜 - 按等级排名
        const query = `
          SELECT 
            c.id,
            c.name,
            c.roleType,
            c.lvl,
            a.hyd
          FROM characters c
          LEFT JOIN character_attributes a ON c.id = a.characterId
          WHERE a.hyd >= 30 AND c.allowLogin = 1
          ORDER BY c.lvl DESC, c.exp DESC
          LIMIT ? OFFSET ?
        `;

        const countQuery = `
          SELECT COUNT(*) as count
          FROM characters c
          LEFT JOIN character_attributes a ON c.id = a.characterId
          WHERE a.hyd >= 30 AND c.allowLogin = 1
        `;

        const results =
          await helpers.characterService.characterRepository.query(query, [
            pageSize,
            offset,
          ]);
        const countResult =
          await helpers.characterService.characterRepository.query(countQuery);

        total = countResult[0]?.count || 0;
        more = "活力值低于 30 不在排行榜出现";

        if (results && Array.isArray(results)) {
          list = results.map((char: any, index: number) => ({
            id: char.id,
            name: char.name,
            roleType: char.roleType,
            num: offset + index + 1,
            content: `(${char.lvl} 级)`,
          }));
        } else {
          console.warn("玩家高手榜查询结果格式异常:", results);
          list = [];
        }
      } else if (type === 2) {
        // 富豪榜 - 按金银排名（银币权重0.0001）
        const query = `
          SELECT 
            c.id,
            c.name,
            c.roleType,
            r.gold,
            r.silver,
            (r.gold + r.silver * 0.0001) as wealth
          FROM characters c
          LEFT JOIN character_resources r ON c.id = r.characterId
          LEFT JOIN character_attributes a ON c.id = a.characterId
          WHERE a.hyd >= 30 AND c.allowLogin = 1
          ORDER BY wealth DESC
          LIMIT ? OFFSET ?
        `;

        const countQuery = `
          SELECT COUNT(*) as count
          FROM characters c
          LEFT JOIN character_attributes a ON c.id = a.characterId
          WHERE a.hyd >= 30 AND c.allowLogin = 1
        `;

        const results =
          await helpers.characterService.characterRepository.query(query, [
            pageSize,
            offset,
          ]);
        const countResult =
          await helpers.characterService.characterRepository.query(countQuery);

        total = countResult[0]?.count || 0;
        more = "活力值低于 30 不在排行榜出现";

        if (results && Array.isArray(results)) {
          list = results.map((char: any, index: number) => ({
            id: char.id,
            name: char.name,
            roleType: char.roleType,
            num: offset + index + 1,
            content: `${char.gold} 金 ${char.silver} 银`,
          }));
        } else {
          console.warn("富豪榜查询结果格式异常:", results);
          list = [];
        }
      } else if (type === 4) {
        // 娱乐榜 - 按本周赢金排名
        const startOfWeek = new Date();
        startOfWeek.setDate(startOfWeek.getDate() - startOfWeek.getDay());
        startOfWeek.setHours(0, 0, 0, 0);

        const query = `
          SELECT 
            c.id,
            c.name,
            c.roleType,
            COALESCE(weekly_wins.total_win, 0) as totalWin
          FROM characters c
          LEFT JOIN character_attributes a ON c.id = a.characterId
          LEFT JOIN (
            SELECT 
              characterId,
              SUM(winAmount) as total_win
            FROM (
              SELECT characterId, winAmount FROM casino_dice_bets 
              WHERE status = 2 AND created_at >= ?
              UNION ALL
              SELECT characterId, (winGold + winSilver) as winAmount FROM casino_chibi_bets 
              WHERE status = 2 AND created_at >= ?
              UNION ALL
              SELECT 
                CASE WHEN winnerId = challengerId THEN challengerId ELSE responderId END as characterId,
                winAmount 
              FROM casino_rock_paper_scissors 
              WHERE status = 2 AND winnerId IS NOT NULL AND created_at >= ?
            ) all_wins
            GROUP BY characterId
          ) weekly_wins ON c.id = weekly_wins.characterId
          WHERE a.hyd >= 30 AND c.allowLogin = 1
          ORDER BY totalWin DESC
          LIMIT ? OFFSET ?
        `;

        const countQuery = `
          SELECT COUNT(*) as count
          FROM characters c
          LEFT JOIN character_attributes a ON c.id = a.characterId
          WHERE a.hyd >= 30 AND c.allowLogin = 1
        `;

        const results =
          await helpers.characterService.characterRepository.query(query, [
            startOfWeek,
            startOfWeek,
            startOfWeek,
            pageSize,
            offset,
          ]);
        const countResult =
          await helpers.characterService.characterRepository.query(countQuery);

        total = countResult[0]?.count || 0;
        more = "活力值低于 30 不在排行榜出现";

        if (results && Array.isArray(results)) {
          list = results.map((char: any, index: number) => ({
            id: char.id,
            name: char.name,
            roleType: char.roleType,
            num: offset + index + 1,
            content: `(赢 ${char.totalWin} 金)`,
          }));
        } else {
          console.warn("娱乐榜查询结果格式异常:", results);
          list = [];
        }
      }

      // 计算页数
      const totalPages = Math.ceil(total / pageSize);

      return {
        act_id: 1192,
        code: 0,
        list,
        more,
        page: totalPages,
        sum: total,
        type,
      };
    } catch (error) {
      console.error("获取排行榜失败:", error);
      return {
        act_id: 1192,
        code: -1,
        msg: "获取排行榜失败",
        list: [],
        more: "",
        page: 0,
        sum: 0,
        type: payload.type || 1,
      };
    }
  },
  // 1193：教派排行榜
  1193: async () => ({ list: [], total: 0, pageNum: 0 }),
  // 1194：副将榜
  1194: async () => ({ list: [], total: 0, pageNum: 0 }),

  // 朋友圈/动态
  // 1160：好友动态-全部
  1160: async () => ({ list: [], pageNum: 0, total: 0 }),
  // 1162：我的动态
  1162: async () => ({ list: [], pageNum: 0, total: 0 }),
  // 1163：关注动态
  1163: async () => ({ list: [], pageNum: 0, total: 0 }),
  // 1164：通知/消息
  1164: async () => ({ list: [], pageNum: 0, total: 0 }),

  // 附近玩家/本地玩家
  // 717：本地玩家列表
  717: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;

      // 获取当前玩家的角色ID
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 717,
          code: 1,
          message: "无法获取玩家角色ID",
          list: [],
          more: 0,
          page: 1,
          sum: 0,
        };
      }

      // 获取玩家当前位置信息
      if (helpers.locationService) {
        const location = await helpers.locationService.getPlayerLocation(
          characterId
        );

        if (!location) {
          return {
            act_id: 717,
            code: 1,
            message: "无法获取玩家位置信息",
            list: [],
            more: 0,
            page: 1,
            sum: 0,
          };
        }

        // 从Redis获取当前区域内的在线玩家列表
        const players = await helpers.locationService.getOnlinePlayersInArea(
          location.areaId
        );

        // 分页处理（每页20个玩家）
        const pageSize = 50;
        const startIndex = pageNum * pageSize;
        const endIndex = startIndex + pageSize;
        const pagePlayers = players.slice(startIndex, endIndex);

        // 格式化玩家数据，符合客户端期望的格式
        const formattedPlayers = pagePlayers.map((player: any) => ({
          id: player.characterId,
          lvl: player.character?.lvl || 1,
          name: player.characterName,
          sex: player.character?.sex || 1,
          state: 0, // 玩家状态，0表示正常
          type: player.character?.roleType || 1, // 职业类型
        }));

        return {
          act_id: 717,
          code: 0,
          list: formattedPlayers,
          more: players.length > endIndex ? 1 : 0, // 是否还有更多数据
          page: pageNum + 1,
          sum: players.length, // 总玩家数量
        };
      }

      // 如果没有位置服务，返回空数据
      return {
        act_id: 717,
        code: 0,
        list: [],
        more: 0,
        page: 1,
        sum: 0,
      };
    } catch (error: any) {
      console.error(`❌ 获取当前地图玩家列表失败:`, error);
      return {
        act_id: 717,
        code: 1,
        message: `获取当前地图玩家列表失败: ${error.message}`,
        list: [],
        more: 0,
        page: 1,
        sum: 0,
      };
    }
  },

  // 签到/积分商店
  // 5309：每日签到-拉取信息
  5309: async (payload, helpers) => {
    try {
      const { roleId } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 5309,
          code: -1,
          msg: "请先选择角色",
          data: null,
        };
      }

      // 这里应该从数据库获取签到信息，暂时返回模拟数据
      // 实际实现时需要创建签到相关的实体和服务
      const signInData = {
        monthCount: 1, // 本月签到次数
        rewardCount: 0, // 已领取奖励次数
        roleId: characterId,
        score: 1, // 签到积分
        todayCount: 1, // 今日签到次数
        todaySignToken: 0, // 今日签到令牌
      };

      return {
        act_id: 5309,
        code: 0,
        data: signInData,
      };
    } catch (error: any) {
      console.error("获取签到信息失败:", error);
      return {
        act_id: 5309,
        code: -1,
        msg: error?.message || "获取签到信息失败",
        data: null,
      };
    }
  },

  // 5310：每日签到-执行（在 gateway 已实现）
  // 5311：积分商店-列表
  5311: async (payload, helpers) => {
    try {
      // 获取积分商城物品列表
      const { pageNum = 0 } = payload;
      const result = await helpers.itemService.getPointShopItems(pageNum, 20);

      // 转换为客户端期望的数据格式
      const data = result.list.map((item: any) => ({
        goodsId: item.id,
        goodsLvl: item.level,
        goodsName: item.name,
        price: item.pointPrice,
      }));

      return {
        act_id: 5311,
        code: 0,
        data: data,
        more: result.total > (pageNum + 1) * result.pageSize ? 1 : 0,
        msg: "1",
      };
    } catch (error: any) {
      console.error("获取积分商店列表失败:", error);
      return {
        act_id: 5311,
        code: -1,
        msg: error?.message || "获取失败",
        data: [],
        more: 0,
      };
    }
  },
  1331: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1331,
          code: -1,
          msg: "请先选择角色",
        };
      }

      // 获取今日在线时长（分钟）
      const todayOnlineMinutes =
        await helpers.playerOnlineTimeService.getTodayOnlineMinutes(
          characterId
        );

      // 体力上限与当前体力
      const basic = await helpers.characterService.getCharacterById(
        characterId
      );
      const maxSinew = helpers.characterService.getSinewCap(basic?.lvl || 1);
      const current = await helpers.characterService.getCharacterInfo(
        characterId
      );
      const currentSinew = Number(current?.sinew || 0);

      // 今日是否已领取在线体力（1374）
      const hasDaily = await helpers.characterService.hasClaimedDailySinew(
        characterId
      );
      // 当前窗口是否已领取（1375）：不在时段视为已领
      const hasWindow = await helpers.characterService.hasClaimedWindowSinew(
        characterId
      );

      // 计算 dubTlz：是否可进入娱乐城（等级>=30 或 VIP>=3）
      let vipLvl = -1;
      try {
        const vipInfo = await (helpers as any).vipService?.queryVipInfo(
          characterId,
          -2
        );
        vipLvl = Number(vipInfo?.vipLvl ?? -1);
      } catch {}
      const canEnterCasino = (basic?.lvl || 0) >= 30 || vipLvl >= 3;

      // 枚举型 sinew（时段体力领取状态）：-1未开启、0可领取、1已领取
      const currentWindow =
        await helpers.characterService.getCurrentSinewWindow();
      let sinewEnum = -1;
      if (currentWindow) {
        sinewEnum = hasWindow ? 1 : 0;
      } else {
        sinewEnum = -1;
      }

      return {
        act_id: 1331,
        code: 0,
        data: {
          dubTlz: canEnterCasino,
          fc: 0,
          happy: canEnterCasino ? 1 : 0,
          max: maxSinew,
          minute: todayOnlineMinutes, // 今日在线分钟
          pk: 0,
          residue: currentSinew,
          sinew: sinewEnum,
          tlz: basic?.lvl || 0,
          today: hasDaily ? 1 : 0,
        },
      };
    } catch (error: any) {
      console.error("获取今日在线时长失败:", error);
      return {
        act_id: 1331,
        code: -1,
        msg: error?.message || "获取在线时长失败",
      };
    }
  },
  // 1375：时间段体力领取（中午/晚上）
  1375: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1375, code: -1, msg: "请先选择角色" };
      }
      const res = await helpers.characterService.claimWindowSinew(characterId);
      return { act_id: 1375, code: 0, msg: res.msg };
    } catch (error: any) {
      return { act_id: 1375, code: -1, msg: error?.message || "领取失败" };
    }
  },
  // 5312：积分商店-兑换
  5312: async () => ({ data: true }),

  // 积分/评分活动
  // 5322：今日积分详情
  5322: async () => ({ list: [] }),
  // 5323：领取积分奖励
  5323: async () => ({ data: true }),
  // 5324：周积分详情
  5324: async () => ({ list: [] }),
  // 5325：周排行
  5325: async () => ({ list: [], pageNum: 0, total: 0 }),

  // 抽奖/老虎机
  // 5327：抽奖（一次或十次）
  5327: async () => ({ reward: null }),
  // 5328：中奖名单
  5328: async () => ({ data: [] }),
  // 5329：我的抽奖记录
  5329: async () => ({ list: [] }),
  // 5330：排行榜（抽奖）
  5330: async () => ({ list: [] }),

  // 师徒/孔庙
  // 1347：招徒/拜师贴列表（t=1/0）
  1347: async () => ({ list: [], pageNum: 0, total: 0 }),
  // 1355：同意/通过申请
  1355: async () => ({ data: true }),
  // 1361：拒绝申请
  1361: async () => ({ data: true }),
  // 1376：申请列表
  1376: async () => ({ list: [], pageNum: 0, total: 0 }),
  // 1379：发起/同意/拒绝师徒申请
  1379: async () => ({ data: true }),

  // VIP（占位已被上方真实实现取代）
  // 6153：VIP 领取奖励
  6153: async (payload, helpers) => {
    try {
      if (!helpers.selectedCharacterId) {
        return { act_id: 6153, code: -1, msg: "请先选择角色" };
      }
      const result = await (helpers as any).vipService.claimVipReward(
        helpers.selectedCharacterId,
        payload || { t: 2, lvl: -1 }
      );
      const rc = (result as any)?.code ?? 0;
      const msg = (result as any)?.msg;
      const data = (result as any)?.data;
      if (rc !== 0) return { act_id: 6153, code: rc, msg: msg || "领取失败" };
      return { act_id: 6153, code: 0, data: data ?? true, msg: msg };
    } catch (e: any) {
      return { act_id: 6153, code: -1, msg: e?.message || "领取失败" };
    }
  },
  // 6154：VIP 选择穿戴（占位已被上方真实实现取代）

  // 组队/队伍消息
  // 42061：队伍消息-列表
  42061: async () => ({ list: [] }),
  // 42062：组队请求-列表
  42062: async () => ({ list: [] }),
  // 42081/42091：同意申请/邀请
  42081: async () => ({ data: true }),
  42091: async () => ({ data: true }),
  // 42082/42092：拒绝申请/邀请
  42082: async () => ({ data: true }),
  42092: async () => ({ data: true }),
  // 4199：刷新队伍消息
  4199: async () => ({ data: true }),

  // 物品查询模块
  // 1120：宝库宝物查询
  1120: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;

      // 获取宝物商店物品列表
      const result = await helpers.basicItemService.getTreasureShopItems(
        pageNum,
        20
      );

      // 转换为客户端期望的数据格式
      const list = result.list.map((item: any) => ({
        id: item.id,
        name: item.name,
        descr: item.description,
        pic: item.pic || "", // 使用数据库中的pic字段
        price: item.goldPrice, // 使用银两价格
      }));

      return {
        act_id: 1120,
        code: 0,
        list: list,
        page: pageNum + 1,
        sum: result.total,
      };
    } catch (error: any) {
      console.error("获取宝库宝物列表失败:", error);
      return {
        act_id: 1120,
        code: -1,
        msg: error?.message || "获取失败",
        list: [],
        page: 1,
        sum: 0,
      };
    }
  },

  // 1199：宝库经验书查询
  1199: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;

      // 获取经验商店物品列表
      const result = await helpers.basicItemService.getExpShopItems(
        pageNum,
        20
      );

      // 转换为客户端期望的数据格式
      const list = result.list.map((item: any) => ({
        id: item.id,
        name: item.name,
        pic: item.pic || "", // 使用数据库中的pic字段
        price: item.goldPrice, // 使用银两价格
      }));

      return {
        act_id: 1199,
        code: 0,
        list: list,
      };
    } catch (error: any) {
      console.error("获取宝库经验书列表失败:", error);
      return {
        act_id: 1199,
        code: -1,
        msg: error?.message || "获取失败",
        list: [],
      };
    }
  },

  // 药品查询 (itemType: 1)
  1121: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;

      // 获取药品类型的物品（itemType: 1）
      const result = await helpers.itemService.getItemsByType(1, pageNum, 20);

      // 转换为客户端期望的数据格式
      const list = result.list.map((item: any) => ({
        id: item.id,
        name: item.name,
        descr: item.description,
        pic: item.picture,
        price: item.silverPrice,
        effectValue: item.effectValue,
      }));

      return {
        act_id: 1121,
        code: 0,
        list: list,
        page: pageNum + 1,
        sum: result.total,
      };
    } catch (error: any) {
      console.error("获取药品列表失败:", error);
      return {
        act_id: 1121,
        code: -1,
        msg: error?.message || "获取失败",
        list: [],
        page: 1,
        sum: 0,
      };
    }
  },

  // 商店物品查询
  1123: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;

      // 获取所有上架商店的物品
      const result = await helpers.itemService.getShopItems(pageNum, 20);

      // 转换为客户端期望的数据格式
      const list = result.list.map((item: any) => ({
        id: item.id,
        name: item.name,
        descr: item.description,
        pic: item.picture,
        price: item.silverPrice,
        goldPrice: item.goldPrice,
        itemType: item.itemType,
        rarity: item.rarity,
      }));

      return {
        act_id: 1123,
        code: 0,
        list: list,
        page: pageNum + 1,
        sum: result.total,
      };
    } catch (error: any) {
      console.error("获取商店物品列表失败:", error);
      return {
        act_id: 1123,
        code: -1,
        msg: error?.message || "获取失败",
        list: [],
        page: 1,
        sum: 0,
      };
    }
  },

  // 物品搜索
  1124: async (payload, helpers) => {
    try {
      const { keyword = "", pageNum = 0 } = payload;

      if (!keyword.trim()) {
        return {
          act_id: 1124,
          code: -1,
          msg: "搜索关键词不能为空",
          list: [],
          page: 1,
          sum: 0,
        };
      }

      // 搜索物品
      const result = await helpers.itemService.searchItems(
        keyword,
        pageNum,
        20
      );

      // 转换为客户端期望的数据格式
      const list = result.list.map((item: any) => ({
        id: item.id,
        name: item.name,
        descr: item.description,
        pic: item.picture,
        price: item.silverPrice,
        goldPrice: item.goldPrice,
        itemType: item.itemType,
        rarity: item.rarity,
      }));

      return {
        act_id: 1124,
        code: 0,
        list: list,
        page: pageNum + 1,
        sum: result.total,
      };
    } catch (error: any) {
      console.error("搜索物品失败:", error);
      return {
        act_id: 1124,
        code: -1,
        msg: error?.message || "搜索失败",
        list: [],
        page: 1,
        sum: 0,
      };
    }
  },

  // 1800：获取副本信息
  1800: async (payload, helpers) => {
    try {
      // 返回固定的副本列表
      const dungeons = [
        {
          fbIng: 0, // 副本进行中状态
          id: 2,
          lvl: 25,
          players_limit: 3,
          site_id: 925,
          time_limit: 30,
          title: "讨伐黄巾军",
          type: 3,
        },
        {
          fbIng: 0,
          id: 4,
          lvl: 30,
          players_limit: 3,
          site_id: 933,
          time_limit: 40,
          title: "虎牢关之战",
          type: 1,
        },
        {
          fbIng: 0,
          id: 5,
          lvl: 40,
          players_limit: 3,
          site_id: 943,
          time_limit: 50,
          title: "讨伐乌桓",
          type: 3,
        },
      ];

      return {
        act_id: 1800,
        code: 0,
        data: dungeons,
        more: 0, // 是否有更多副本
      };
    } catch (error: any) {
      console.error("获取副本信息失败:", error);
      return {
        act_id: 1800,
        code: -1,
        msg: error.message || "获取失败",
        data: [],
        more: 0,
      };
    }
  },

  // ==================== 背包查询模块 ====================

  // 1416：查询背包药品信息
  1416: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1416,
          code: -1,
          msg: "请先选择角色",
          list: [],
          page: 1,
          sum: 0,
        };
      }

      const result =
        await helpers.characterMedicineService.getCharacterMedicine(
          characterId,
          pageNum,
          20
        );

      return {
        act_id: 1416,
        code: 0,
        list: result.list,
        page: result.page,
        sum: result.sum,
      };
    } catch (error: any) {
      console.error("查询背包药品失败:", error);
      return {
        act_id: 1416,
        code: -1,
        msg: error?.message || "查询失败",
        list: [],
        page: 1,
        sum: 0,
      };
    }
  },

  // 1476：查询负重信息（返回 [当前负重, 最大负重]）
  1476: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1476, code: -1, msg: "请先选择角色", data: null };
      }
      const { currentWeight, maxWeight } =
        await helpers.characterAttributeService.computeWeights(characterId);
      return { act_id: 1476, code: 0, data: [currentWeight, maxWeight] };
    } catch (error: any) {
      console.error("查询负重失败:", error);
      return { act_id: 1476, code: -1, msg: error?.message || "查询失败" };
    }
  },

  // 1423：查询背包状态
  1423: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1423,
          code: -1,
          msg: "请先选择角色",
          list: [],
          page: 1,
          sum: 0,
        };
      }

      const result = await helpers.inventoryService.getCharacterStatus(
        characterId,
        pageNum,
        20
      );

      return {
        act_id: 1423,
        code: 0,
        list: result.list,
        page: result.page,
        sum: result.sum,
        resources: result.resources,
      };
    } catch (error: any) {
      console.error("查询背包状态失败:", error);
      return {
        act_id: 1423,
        code: -1,
        msg: error?.message || "查询失败",
        list: [],
        page: 1,
        sum: 0,
      };
    }
  },

  // 6034：查询背包宝石
  6034: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 6034,
          code: -1,
          msg: "请先选择角色",
          list: [],
          page: 1,
          sum: 0,
        };
      }

      const result = await helpers.gemService.getCharacterGems(
        characterId,
        pageNum,
        20
      );

      return {
        act_id: 6034,
        code: 0,
        list: result.list,
        page: result.page,
        sum: result.sum,
      };
    } catch (error: any) {
      console.error("查询背包宝石失败:", error);
      return {
        act_id: 6034,
        code: -1,
        msg: error?.message || "查询失败",
        list: [],
        page: 1,
        sum: 0,
      };
    }
  },

  // 1909：副将碎片合成副将（消耗10个碎片，发放对应副将）
  1909: async (payload, helpers) => {
    try {
      const { gid } = payload || {};
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1909, code: -1, msg: "请先选择角色" };
      }
      if (!gid) {
        return { act_id: 1909, code: -1, msg: "缺少碎片物品gid" };
      }
      const result =
        await helpers.deputyGeneralService.composeDeputyFromFragment(
          Number(characterId),
          Number(gid)
        );
      return {
        act_id: 1909,
        code: 0,
        msg: "合成成功",
        data: result,
      };
    } catch (error: any) {
      return {
        act_id: 1909,
        code: -1,
        msg: error?.message || "合成失败",
      };
    }
  },

  // 1284：宝石合成列表查询（同级可用于合成的宝石）
  1284: async (payload, helpers) => {
    try {
      const { lvl = 1, pageNum = 0 } = payload || {};
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return {
          act_id: 1284,
          code: -1,
          msg: "请先选择角色",
          list: [],
          page: 0,
          sum: 0,
        };
      }
      const result = await helpers.gemService.listCombinableGems(
        Number(characterId),
        Number(lvl),
        Number(pageNum),
        40
      );
      return {
        act_id: 1284,
        code: 0,
        list: result.list,
        page: result.page,
        sum: result.sum,
      };
    } catch (error: any) {
      return {
        act_id: 1284,
        code: -1,
        msg: error?.message || "查询失败",
        list: [],
        page: 0,
        sum: 0,
      };
    }
  },

  // 1286：宝石合成（两颗同级 → 一颗更高一级，属性随机）
  1286: async (payload, helpers) => {
    try {
      const { s1, s2 } = payload || {};
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1286, code: -1, msg: "请先选择角色" };
      }
      if (!s1 || !s2) {
        return { act_id: 1286, code: -1, msg: "缺少宝石ID" };
      }
      // 从 1274/vip 服务推断可合成上限（若可用）
      let maxAllowedLevel: number | undefined = undefined;
      try {
        if (
          helpers.vipService &&
          typeof helpers.vipService.getVipComposeMaxLevel === "function"
        ) {
          maxAllowedLevel = await helpers.vipService.getVipComposeMaxLevel(
            characterId
          );
        }
      } catch {}
      const res = await helpers.gemService.combineTwoGems(
        Number(characterId),
        Number(s1),
        Number(s2),
        typeof maxAllowedLevel === "number" ? maxAllowedLevel : undefined
      );
      return {
        act_id: 1286,
        code: 0,
        msg: `成功合成获得${res.level}${res.baseName}`,
        data: res.newGem,
      };
    } catch (error: any) {
      return { act_id: 1286, code: -1, msg: error?.message || "合成失败" };
    }
  },

  // 1090：根据宝石ID查询可以镶嵌的装备
  1090: async (payload, helpers) => {
    try {
      const { id: gemInventoryId } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1090,
          code: -1,
          msg: "请先选择角色",
          data: [],
        };
      }

      if (!gemInventoryId) {
        return {
          act_id: 1090,
          code: -1,
          msg: "宝石ID不能为空",
          data: [],
        };
      }

      const result = await helpers.gemService.getSocketableEquipment(
        characterId,
        gemInventoryId
      );

      return {
        act_id: 1090,
        code: result.success ? 0 : -1,
        msg: result.message,
        data: result.data || [],
      };
    } catch (error: any) {
      console.error("查询可镶嵌装备失败:", error);
      return {
        act_id: 1090,
        code: -1,
        msg: error?.message || "查询失败",
        data: [],
      };
    }
  },

  // 1092：将宝石镶嵌到对应装备上
  1092: async (payload, helpers) => {
    try {
      const { id: gemInventoryId, aid: equipmentId } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1092,
          code: -1,
          msg: "请先选择角色",
          data: "",
        };
      }

      if (!gemInventoryId || typeof gemInventoryId !== "number") {
        return {
          act_id: 1092,
          code: -1,
          msg: "宝石ID不能为空且必须为数字",
          data: "",
        };
      }

      if (!equipmentId || typeof equipmentId !== "number") {
        return {
          act_id: 1092,
          code: -1,
          msg: "装备ID不能为空且必须为数字",
          data: "",
        };
      }

      const result = await helpers.gemService.socketGemToEquipment(
        characterId,
        gemInventoryId,
        equipmentId
      );

      return {
        act_id: 1092,
        code: result.success ? 0 : -1,
        msg: result.message,
        data: result.success ? result.message : "",
      };
    } catch (error: any) {
      console.error("宝石镶嵌失败:", error);
      return {
        act_id: 1092,
        code: -1,
        msg: error?.message || "镶嵌失败",
        data: "",
      };
    }
  },

  // 1094：装备洗孔
  1094: async (payload, helpers) => {
    try {
      const { id: equipmentId, i: socketSlot } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1094,
          code: -1,
          msg: "请先选择角色",
        };
      }

      if (!equipmentId || !socketSlot) {
        return {
          act_id: 1094,
          code: -1,
          msg: "参数错误：装备ID和槽位位置不能为空",
        };
      }

      if (socketSlot < 1 || socketSlot > 3) {
        return {
          act_id: 1094,
          code: -1,
          msg: "槽位位置错误：必须是1、2或3",
        };
      }

      // 调用宝石服务的洗孔方法
      const result = await helpers.gemService.washSocket(
        characterId,
        equipmentId,
        socketSlot
      );

      if (result.success) {
        return {
          act_id: 1094,
          code: 0,
          msg: result.message,
        };
      } else {
        return {
          act_id: 1094,
          code: -1,
          msg: result.message,
        };
      }
    } catch (error: any) {
      console.error("处理装备洗孔指令1094失败:", error);
      return {
        act_id: 1094,
        code: -1,
        msg: error?.message || "洗孔失败",
      };
    }
  },

  // 2032：开矿生成宝石
  2032: async (payload, helpers) => {
    try {
      const { id } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 2032,
          code: -1,
          msg: "请先选择角色",
          data: "请先选择角色",
        };
      }

      if (!id) {
        return {
          act_id: 2032,
          code: -1,
          msg: "矿洞ID不能为空",
          data: "矿洞ID不能为空",
        };
      }

      // 根据ID确定矿洞类型
      let miningType = 1; // 默认原矿
      let keyItemId = 157; // 原木钥匙

      switch (id) {
        case 155: // 精钢宝盒
          miningType = 2;
          keyItemId = 158; // 精钢钥匙
          break;
        case 156: // 珍奇宝盒
        case 432: // 珍奇宝盒绑
          miningType = 3;
          keyItemId = 159; // 珍奇钥匙
          break;
        case 154: // 原木宝盒
        default:
          miningType = 1;
          keyItemId = 157; // 原木钥匙
          break;
      }

      const result = await helpers.gemService.mineGems(
        characterId,
        miningType,
        keyItemId,
        id
      );

      if (result.success) {
        // 构建宝石描述文本
        let dataDescription = "";
        if (result.gems && result.gems.length > 0) {
          const gemNames = result.gems
            .map((gem: any) => `${gem.name}(等级${gem.level})`)
            .join("、");
          dataDescription = `成功获得宝石：${gemNames}`;
        } else {
          dataDescription = "开矿成功，但未获得宝石";
        }

        return {
          act_id: 2032,
          code: 0,
          msg: result.message,
          data: dataDescription,
        };
      } else {
        return {
          act_id: 2032,
          code: 8,
          msg: result.message,
          data: result.message,
        };
      }
    } catch (error: any) {
      console.error("开矿失败:", error);
      return {
        act_id: 2032,
        code: -1,
        msg: error?.message || "开矿失败",
        data: error?.message || "开矿失败",
      };
    }
  },

  // 2031：开矿生成宝石（与2032一致，兼容旧前端）
  2031: async (payload, helpers) => {
    try {
      // 复用 2032 逻辑
      const res = await (async () => {
        const { id } = payload;
        const characterId = helpers.selectedCharacterId;
        if (!characterId) {
          return {
            act_id: 2031,
            code: -1,
            msg: "请先选择角色",
            data: "请先选择角色",
          };
        }
        if (!id) {
          return {
            act_id: 2031,
            code: -1,
            msg: "矿洞ID不能为空",
            data: "矿洞ID不能为空",
          };
        }
        let miningType = 1; // 原矿
        let keyItemId = 157; // 原木钥匙
        switch (id) {
          case 155:
            miningType = 2;
            keyItemId = 158;
            break; // 精钢
          case 156:
          case 432:
            miningType = 3;
            keyItemId = 159;
            break; // 珍奇
          case 154:
          default:
            miningType = 1;
            keyItemId = 157;
            break; // 原木
        }
        const result = await helpers.gemService.mineGems(
          characterId,
          miningType,
          keyItemId,
          id
        );
        if (result.success) {
          let dataDescription = "";
          if (result.gems && result.gems.length > 0) {
            const gemNames = (
              result.gems as Array<{ name: string; level: number }>
            )
              .map((g) => `${g.name}(等级${g.level})`)
              .join("、");
            dataDescription = `成功获得宝石：${gemNames}`;
          } else {
            dataDescription = "开矿成功，但未获得宝石";
          }
          return {
            act_id: 2031,
            code: 0,
            msg: result.message,
            data: dataDescription,
          };
        }
        return {
          act_id: 2031,
          code: 8,
          msg: result.message,
          data: result.message,
        };
      })();
      return res;
    } catch (error: any) {
      return {
        act_id: 2031,
        code: -1,
        msg: error?.message || "开矿失败",
        data: error?.message || "开矿失败",
      };
    }
  },

  // 6035：镶嵌宝石到装备
  6035: async (payload, helpers) => {
    try {
      const { equipmentId, equipmentType, socketSlot, gemInventoryId } =
        payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 6035,
          code: -1,
          msg: "请先选择角色",
        };
      }

      if (!equipmentId || !equipmentType || !socketSlot || !gemInventoryId) {
        return {
          act_id: 6035,
          code: -1,
          msg: "参数不完整",
        };
      }

      const result = await helpers.gemService.socketGem(
        characterId,
        equipmentId,
        equipmentType,
        socketSlot,
        gemInventoryId
      );

      return {
        act_id: 6035,
        code: result.success ? 0 : -1,
        msg: result.message,
      };
    } catch (error: any) {
      console.error("镶嵌宝石失败:", error);
      return {
        act_id: 6035,
        code: -1,
        msg: error?.message || "镶嵌宝石失败",
      };
    }
  },

  // 6036：卸下装备上的宝石
  6036: async (payload, helpers) => {
    try {
      const { equipmentId, equipmentType, socketSlot } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 6036,
          code: -1,
          msg: "请先选择角色",
        };
      }

      if (!equipmentId || !equipmentType || !socketSlot) {
        return {
          act_id: 6036,
          code: -1,
          msg: "参数不完整",
        };
      }

      const result = await helpers.gemService.unsocketGem(
        characterId,
        equipmentId,
        equipmentType,
        socketSlot
      );

      return {
        act_id: 6036,
        code: result.success ? 0 : -1,
        msg: result.message,
      };
    } catch (error: any) {
      console.error("卸下宝石失败:", error);
      return {
        act_id: 6036,
        code: -1,
        msg: error?.message || "卸下宝石失败",
      };
    }
  },

  // 6037：查询装备宝石镶嵌信息
  6037: async (payload, helpers) => {
    try {
      const { equipmentId, equipmentType } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 6037,
          code: -1,
          msg: "请先选择角色",
          data: [],
        };
      }

      if (!equipmentId || !equipmentType) {
        return {
          act_id: 6037,
          code: -1,
          msg: "参数不完整",
          data: [],
        };
      }

      const gems = await helpers.gemService.getEquipmentGems(
        characterId,
        equipmentId,
        equipmentType
      );

      return {
        act_id: 6037,
        code: 0,
        data: gems,
      };
    } catch (error: any) {
      console.error("查询装备宝石信息失败:", error);
      return {
        act_id: 6037,
        code: -1,
        msg: error?.message || "查询失败",
        data: [],
      };
    }
  },

  // 1425：查询背包杂物
  1425: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1425,
          code: -1,
          msg: "请先选择角色",
          data: [],
          page: 1,
          sum: 0,
        };
      }

      // 杂物查询不需要分页，直接获取所有杂物
      const result = await helpers.inventoryService.getCharacterMisc(
        characterId,
        0, // 固定为第0页
        1000 // 获取足够多的物品
      );

      return {
        act_id: 1425,
        code: 0,
        data: result.data,
        page: 1,
        num: result.sum,
      };
    } catch (error: any) {
      console.error("查询背包杂物失败:", error);
      return {
        act_id: 1425,
        code: -1,
        msg: error?.message || "查询失败",
        data: [],
        page: 1,
        sum: 0,
      };
    }
  },

  // ==================== 月卡系统模块 ====================

  // 6600：查询月卡状态
  6600: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return { act_id: 6600, code: -1, msg: "请先选择角色", data: null };
      }

      // 获取角色的月卡状态
      const monthlyCards =
        await helpers.monthlyCardService.getCharacterMonthlyCardsForFrontend(
          characterId
        );

      return {
        act_id: 6600,
        code: 0,
        data: { cards: monthlyCards },
      };
    } catch (error: any) {
      console.error("查询月卡状态失败:", error);
      return {
        act_id: 6600,
        code: -1,
        msg: error?.message || "查询失败",
        data: null,
      };
    }
  },

  // 6603：购买月卡
  6603: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      const { gold } = payload;

      if (!characterId) {
        return { act_id: 6603, code: -1, msg: "请先选择角色", data: null };
      }

      if (!gold) {
        return { act_id: 6603, code: -1, msg: "金币数量不能为空", data: null };
      }

      // 根据金币数量确定月卡类型
      let cardType;
      if (gold === 13000) {
        cardType = 38; // 小月卡
      } else if (gold === 33000) {
        cardType = 98; // 大月卡
      } else {
        return { act_id: 6603, code: -1, msg: "无效的月卡价格", data: null };
      }

      // 购买月卡
      const result = await helpers.monthlyCardService.purchaseMonthlyCard(
        characterId,
        cardType
      );

      return {
        act_id: 6603,
        code: 0,
        data: result,
        msg: result.message,
      };
    } catch (error: any) {
      console.error("购买月卡失败:", error);
      return {
        act_id: 6603,
        code: -1,
        msg: error?.message || "购买失败",
        data: null,
      };
    }
  },

  // 6601：领取月卡奖励
  6601: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      const { card } = payload;

      if (!characterId) {
        return { act_id: 6601, code: -1, msg: "请先选择角色", data: null };
      }

      if (!card) {
        return { act_id: 6601, code: -1, msg: "月卡类型不能为空", data: null };
      }

      // 领取每日奖励
      const result = await helpers.monthlyCardService.claimDailyReward(
        characterId,
        parseInt(card)
      );

      return {
        act_id: 6601,
        code: 0,
        data: result,
        msg: result.message,
      };
    } catch (error: any) {
      console.error("领取月卡奖励失败:", error);
      return {
        act_id: 6601,
        code: -1,
        msg: error?.message || "领取失败",
        data: null,
      };
    }
  },

  // 6602：月卡数据更新（前端监听用）
  6602: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return { act_id: 6602, code: -1, msg: "请先选择角色" };
      }

      // 6602指令仅用于监听，返回简单成功响应
      return {
        act_id: 6602,
        code: 0,
      };
    } catch (error: any) {
      console.error("月卡数据更新失败:", error);
      return {
        act_id: 6602,
        code: -1,
        msg: error?.message || "更新失败",
      };
    }
  },

  // 6609：重置今日奖励状态（测试用）
  6609: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      const { card } = payload || {};

      if (!characterId) {
        return { act_id: 6609, code: -1, msg: "请先选择角色", data: null };
      }

      const parsedCard =
        card === undefined || card === null || card === ""
          ? undefined
          : parseInt(card);
      const count = await helpers.monthlyCardService.resetDailyRewardStatus(
        characterId,
        parsedCard
      );

      return {
        act_id: 6609,
        code: 0,
        data: { resetCount: count },
        msg: "已重置今日领取状态",
      };
    } catch (error: any) {
      console.error("重置今日月卡领取状态失败:", error);
      return {
        act_id: 6609,
        code: -1,
        msg: error?.message || "重置失败",
        data: null,
      };
    }
  },

  // 1203：商城金币购买
  1203: async (payload, helpers) => {
    try {
      if (!helpers.selectedCharacterId) {
        return { act_id: 1203, code: -1, msg: "请先选择角色", data: null };
      }

      const { gid, count = 1 } = payload;

      if (!gid) {
        return { act_id: 1203, code: -1, msg: "商品ID不能为空", data: null };
      }

      if (count <= 0) {
        return { act_id: 1203, code: -1, msg: "购买数量必须大于0", data: null };
      }

      // 调用商店服务进行金币购买
      const result = await helpers.shopService.purchaseWithGold(
        helpers.selectedCharacterId,
        gid,
        count
      );

      return {
        act_id: 1203,
        code: 0,
        data: result.goods,
        msg: result.message,
      };
    } catch (error: any) {
      console.error("商城金币购买失败:", error);

      // 根据错误类型返回不同的错误码
      if (error.message.includes("金币不足")) {
        return { act_id: 1203, code: 8, msg: "金不够!", data: null };
      } else if (error.message.includes("商品不存在")) {
        return { act_id: 1203, code: -1, msg: "商品不存在", data: null };
      } else if (error.message.includes("等级不足")) {
        return { act_id: 1203, code: -1, msg: error.message, data: null };
      } else if (error.message.includes("不支持金币购买")) {
        return {
          act_id: 1203,
          code: -1,
          msg: "该商品不支持金币购买",
          data: null,
        };
      } else {
        return {
          act_id: 1203,
          code: -1,
          msg: error.message || "购买失败",
          data: null,
        };
      }
    }
  },

  // 1249：医馆银币购买
  1249: async (payload, helpers) => {
    try {
      if (!helpers.selectedCharacterId) {
        return { act_id: 1249, code: -1, msg: "请先选择角色", data: null };
      }

      const { goodsId, count = 1, silverType = 0, retType = 0 } = payload;

      if (!goodsId) {
        return { act_id: 1249, code: -1, msg: "商品ID不能为空", data: null };
      }

      if (count <= 0) {
        return { act_id: 1249, code: -1, msg: "购买数量必须大于0", data: null };
      }

      // 负重校验：药品每个负重1
      const { currentWeight, maxWeight } =
        await helpers.characterAttributeService.computeWeights(
          helpers.selectedCharacterId
        );
      if (currentWeight + count > maxWeight) {
        return {
          act_id: 1249,
          code: -1,
          msg: "负重已满，无法购买",
          data: null,
        };
      }

      // 调用商店服务进行银币购买
      const result = await helpers.shopService.purchaseWithSilver(
        helpers.selectedCharacterId,
        goodsId,
        count,
        silverType
      );

      // 查询物品信息来判断是否为药品
      const item = await helpers.basicItemService.getItemById(goodsId);

      // 如果是药品，只添加到药品表，不添加到背包杂物表
      if (
        true //默认这个指令只用于药品购买
        // item &&
        // item.name &&
        // (item.name.includes("药") ||
        //   item.name.includes("丸") ||
        //   item.name.includes("丹"))
      ) {
        try {
          await helpers.characterMedicineService.addMedicineToInventory(
            helpers.selectedCharacterId,
            goodsId,
            count
          );
        } catch (error) {
          console.error("添加药品到药品表失败:", error);
          // 如果添加到药品表失败，需要回滚购买操作
          throw new Error("购买成功但添加到药品表失败，请重试");
        }
      } else {
        // 非药品物品，添加到背包杂物表
        try {
          await helpers.inventoryService.addItemToInventory(
            helpers.selectedCharacterId,
            goodsId,
            count
          );
        } catch (error) {
          console.error("添加物品到背包失败:", error);
          // 如果添加到背包失败，需要回滚购买操作
          throw new Error("购买成功但添加到背包失败，请重试");
        }
      }

      return {
        act_id: 1249,
        code: 0,
        data: `您成功购买了 ${count} 个${result.goods.name}`,
      };
    } catch (error: any) {
      console.error("医馆银币购买失败:", error);

      // 根据错误类型返回不同的错误码
      if (error.message.includes("银币不足")) {
        return { act_id: 1249, code: 8, msg: "您的资金不足", data: null };
      } else if (error.message.includes("商品不存在")) {
        return { act_id: 1249, code: -1, msg: "商品不存在", data: null };
      } else if (error.message.includes("等级不足")) {
        return { act_id: 1249, code: -1, msg: error.message, data: null };
      } else if (error.message.includes("不支持银币购买")) {
        return {
          act_id: 1249,
          code: -1,
          msg: "该商品不支持银币购买",
          data: null,
        };
      } else if (error.message.includes("无效的银币类型")) {
        return { act_id: 1249, code: -1, msg: "无效的银币类型", data: null };
      } else {
        return {
          act_id: 1249,
          code: -1,
          msg: error.message || "购买失败",
          data: null,
        };
      }
    }
  },

  // 副将基础数据查询模块
  // 1102：根据星级查询副将列表
  1102: async (payload, helpers) => {
    try {
      const { s: starLevel, t: sortType, pageNum = 0 } = payload || {};

      if (!starLevel) {
        return { act_id: 1102, code: -1, msg: "星级参数不能为空", data: null };
      }

      if (!sortType) {
        return {
          act_id: 1102,
          code: -1,
          msg: "排序类型参数不能为空",
          data: null,
        };
      }

      // 调用副将服务查询数据（使用真实分页查询）
      const result =
        await helpers.deputyGeneralService.getDeputyGeneralsByStarLevel(
          Number(starLevel),
          Number(sortType),
          pageNum
        );

      return {
        act_id: 1102,
        code: 0,
        list: result.list,
        page: result.page,
        sum: result.totalCount, // 按照文档格式返回
      };
    } catch (error: any) {
      console.error("查询副将列表失败:", error);
      return {
        act_id: 1102,
        code: -1,
        msg: error.message || "查询副将列表失败",
        data: null,
      };
    }
  },

  // 1201：根据ID查询副将详情
  1201: async (payload, helpers) => {
    try {
      const { id } = payload || {};

      if (!id) {
        return { act_id: 1201, code: -1, msg: "副将ID不能为空", data: null };
      }

      // 调用副将服务查询详情
      const data = await helpers.deputyGeneralService.getDeputyGeneralById(id);

      return {
        act_id: 1201,
        code: 0,
        data: data,
      };
    } catch (error: any) {
      console.error("查询副将详情失败:", error);
      return {
        act_id: 1201,
        code: -1,
        msg: error.message || "查询副将详情失败",
        data: null,
      };
    }
  },

  // 5280：查询大小玩法中奖名单
  5280: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload || {};

      // 调用娱乐城服务获取大小玩法中奖名单
      const result = await helpers.casinoService.getDiceWinners(pageNum);

      return result;
    } catch (error: any) {
      console.error("查询大小玩法中奖名单失败:", error);
      return {
        act_id: 5280,
        code: -1,
        msg: error.message || "查询大小玩法中奖名单失败",
        list: [],
      };
    }
  },

  // 1340：查看大小奖励排行
  1340: async (payload, helpers) => {
    try {
      const { pageNum = 0 } = payload || {};

      // 调用娱乐城服务获取大小玩法赢取金额排行榜
      const result = await helpers.casinoService.getDiceWinAmountRankings(
        pageNum
      );

      return result;
    } catch (error: any) {
      console.error("查询大小玩法赢取金额排行榜失败:", error);
      return {
        act_id: 1340,
        code: -1,
        msg: error.message || "查询大小玩法赢取金额排行榜失败",
        list: [],
      };
    }
  },

  // 位置相关指令
  // 1002：获取指定区域玩家列表
  1002: async (payload, helpers) => {
    try {
      const { areaId } = payload;

      if (!areaId) {
        return {
          act_id: 1002,
          code: 1,
          message: "区域ID不能为空",
          data: null,
        };
      }

      // 从Redis获取区域内的在线玩家列表
      if (helpers.locationService) {
        const players = await helpers.locationService.getOnlinePlayersInArea(
          areaId
        );

        return {
          act_id: 1002,
          code: 0,
          message: "获取成功",
          data: {
            areaId,
            playerCount: players.length,
            players,
          },
        };
      }

      return {
        act_id: 1002,
        code: 0,
        message: "获取成功",
        data: {
          areaId,
          playerCount: 0,
          players: [],
        },
      };
    } catch (error: any) {
      console.error(`❌ 获取区域玩家列表失败:`, error);
      return {
        act_id: 1002,
        code: 1,
        message: `获取失败: ${error.message}`,
        data: null,
      };
    }
  },

  // 1008：设置玩家在线状态
  1008: async (payload, helpers) => {
    try {
      const { characterId, isOnline } = payload;

      if (!characterId || isOnline === undefined) {
        return {
          act_id: 1008,
          code: 1,
          message: "角色ID和在线状态不能为空",
          data: null,
        };
      }

      // 调用位置服务设置在线状态（会自动同步到Redis）
      if (helpers.locationService) {
        await helpers.locationService.setPlayerOnlineStatus(
          characterId,
          isOnline
        );
      }

      return {
        act_id: 1008,
        code: 0,
        message: isOnline ? "上线成功" : "下线成功",
        data: { characterId, isOnline },
      };
    } catch (error: any) {
      console.error(`❌ 设置玩家在线状态失败:`, error);
      return {
        act_id: 1008,
        code: 1,
        message: `状态设置失败: ${error.message}`,
        data: null,
      };
    }
  },

  // 1007：获取玩家当前位置
  1007: async (payload, helpers) => {
    try {
      const { characterId } = payload;

      if (!characterId) {
        return {
          act_id: 1007,
          code: 1,
          message: "角色ID不能为空",
          data: null,
        };
      }

      // 获取玩家当前位置信息
      if (helpers.locationService) {
        const location = await helpers.locationService.getPlayerLocation(
          characterId
        );

        if (!location) {
          return {
            act_id: 1007,
            code: 1,
            message: "无法获取玩家位置信息",
            data: null,
          };
        }

        return {
          act_id: 1007,
          code: 0,
          message: "获取成功",
          data: location,
        };
      }

      return {
        act_id: 1007,
        code: 0,
        message: "获取成功",
        data: null,
      };
    } catch (error: any) {
      console.error(`❌ 获取玩家位置失败:`, error);
      return {
        act_id: 1007,
        code: 1,
        message: `获取失败: ${error.message}`,
        data: null,
      };
    }
  },

  // 1475：软删除角色
  1475: async (payload, helpers) => {
    try {
      const { roleid } = payload;

      if (!roleid) {
        return {
          act_id: 1475,
          code: 1,
          message: "角色ID不能为空",
          data: null,
        };
      }

      // 调用角色服务执行软删除
      const result = await helpers.characterService.softDeleteCharacter(
        roleid,
        helpers.userId
      );

      if (result.success) {
        return {
          act_id: 1475,
          code: 0,
          message: result.message,
          data: { roleid },
        };
      } else {
        return {
          act_id: 1475,
          code: 1,
          message: result.message,
          data: null,
        };
      }
    } catch (error: any) {
      console.error(`❌ 软删除角色失败:`, error);
      return {
        act_id: 1475,
        code: 1,
        message: `删除失败: ${error.message}`,
        data: null,
      };
    }
  },
  // 1200：查询背包中将军令数量
  1200: async (payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1200,
          code: -1,
          msg: "请先选择角色",
          data: {
            djjl: 0,
            djjl_bd: 0,
            jjl: 0,
            jjl_bd: 0,
          },
        };
      }

      const result = await helpers.inventoryService.getGeneralTokenCounts(
        characterId
      );

      return {
        act_id: 1200,
        code: 0,
        data: result,
      };
    } catch (error: any) {
      console.error("查询将军令数量失败:", error);
      return {
        act_id: 1200,
        code: -1,
        msg: error?.message || "查询失败",
        data: {
          djjl: 0,
          djjl_bd: 0,
          jjl: 0,
          jjl_bd: 0,
        },
      };
    }
  },

  // 1265：杂物查询指令
  1265: async (payload, helpers) => {
    try {
      const { t, pageNum = 0 } = payload;

      // 验证参数
      if (typeof t !== "number" || ![2, 3].includes(t)) {
        return {
          act_id: 1265,
          code: -1,
          msg: "无效的类型参数，t必须是2或3",
          list: [],
        };
      }

      // 定义杂物物品ID数组
      const miscItemIds: Record<number, number[]> = {
        // t=3: 杂物类
        3: [71, 72, 74, 75, 108, 109],
        // t=2: 矿物类
        2: [
          58, 38, 48, 39, 49, 59, 60, 50, 40, 61, 41, 51, 62, 42, 52, 63, 53,
          43, 54, 44, 64, 55, 45, 65, 56, 46, 66, 57, 47, 67,
        ],
      };

      // 获取对应类型的物品ID列表
      const itemIds = miscItemIds[t];
      if (!itemIds || itemIds.length === 0) {
        return {
          act_id: 1265,
          code: 0,
          list: [],
        };
      }

      // 查询数据库中的物品
      const items = await helpers.basicItemService.getItemsByIds(itemIds);

      // 转换为标准格式
      const list = items.map((item: any) => ({
        id: item.id,
        name: item.name,
        pic: item.pic || "none.png",
        price: item.silverPrice,
      }));

      return {
        act_id: 1265,
        code: 0,
        list: list,
      };
    } catch (error: any) {
      console.error("处理杂物查询指令1265失败:", error);
      return {
        act_id: 1265,
        code: -1,
        msg: "查询失败",
        list: [],
      };
    }
  },

  // 1060：药品信息查询指令
  1060: async (payload, helpers) => {
    try {
      const { gid } = payload;

      // 验证参数
      if (!gid || typeof gid !== "number") {
        return {
          act_id: 1060,
          code: -1,
          msg: "药品ID不能为空且必须为数字",
          data: [],
        };
      }

      // 查询药品信息
      const item = await helpers.basicItemService.getItemById(gid);

      if (!item) {
        return {
          act_id: 1060,
          code: -1,
          msg: "药品不存在",
          data: [],
        };
      }

      // 构建返回数据格式
      const data = [
        { k: "名称:", v: item.name },
        { k: "价格:", v: item.silverPrice || "0" }, // 使用silverPrice作为精力值
        { k: "等级:", v: item.lv?.toString() || "1" },
        { k: "介绍:", v: item.description || "暂无介绍" },
      ];

      return {
        act_id: 1060,
        code: 0,
        data: data,
      };
    } catch (error: any) {
      console.error("处理药品信息查询指令1060失败:", error);
      return {
        act_id: 1060,
        code: -1,
        msg: "查询失败",
        data: [],
      };
    }
  },

  // 1267：物品基础表查询指令
  1267: async (payload, helpers) => {
    try {
      const { id } = payload;

      // 验证参数
      if (!id || typeof id !== "number") {
        return {
          act_id: 1267,
          code: -1,
          msg: "物品ID不能为空且必须为数字",
          data: [],
        };
      }

      // 查询物品信息
      const item = await helpers.basicItemService.getItemById(id);

      if (!item) {
        return {
          act_id: 1267,
          code: -1,
          msg: "物品不存在",
          data: [],
        };
      }

      // 构建返回数据格式
      const data = [
        { k: "名称:", v: item.name },
        { k: "价格:", v: `${item.silverPrice}两` },
        { k: "等级:", v: item.lv.toString() },
        { k: "负重:", v: item.weight.toString() },
        { k: "介绍:", v: item.description },
      ];

      return {
        act_id: 1267,
        code: 0,
        data: data,
      };
    } catch (error: any) {
      console.error("处理物品基础表查询指令1267失败:", error);
      return {
        act_id: 1267,
        code: -1,
        msg: "查询失败",
        data: [],
      };
    }
  },

  // 1269：银币购买功能
  1269: async (payload, helpers) => {
    try {
      const { id, count, type } = payload;

      // 验证参数
      if (!id || !count || count <= 0) {
        return {
          act_id: 1269,
          code: -1,
          msg: "物品ID和数量不能为空，且数量必须大于0",
        };
      }

      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return {
          act_id: 1269,
          code: -1,
          msg: "请先选择角色",
        };
      }

      // 使用事务处理银币购买
      const result = await helpers.shopService.purchaseWithSilver(
        characterId,
        parseInt(id),
        parseInt(count),
        type || 0
      );

      if (result.success) {
        return {
          act_id: 1269,
          code: 0,
        };
      } else {
        return {
          act_id: 1269,
          code: -1,
          msg: result.message || "购买失败",
        };
      }
    } catch (error: any) {
      console.error("处理银币购买指令1269失败:", error);
      return {
        act_id: 1269,
        code: -1,
        msg: error?.message || "购买失败",
      };
    }
  },

  // 713：NPC集群详细信息查询指令
  713: async (payload, helpers) => {
    try {
      const { id } = payload;

      // 验证参数
      if (!id || typeof id !== "number") {
        return {
          act_id: 713,
          code: -1,
          msg: "NPC集群ID不能为空且必须为数字",
          data: [],
        };
      }

      // 查询NPC集群详细信息
      const npcDetails = await helpers.npcService.getNpcDetailById(id);

      return {
        act_id: 713,
        code: 0,
        data: npcDetails,
      };
    } catch (error: any) {
      console.error("处理NPC集群详细信息查询指令713失败:", error);
      return {
        act_id: 713,
        code: -1,
        msg: error?.message || "查询NPC集群详细信息失败",
        data: [],
      };
    }
  },

  // 坐骑系统模块 - 使用专门的坐骑处理器
  // 4423：获取坐骑基础列表
  4423: async (payload, helpers) => {
    if (mountWsHandlers[4423]) {
      return await mountWsHandlers[4423](payload, helpers);
    }
    return { act_id: 4423, code: -1, msg: "坐骑处理器未找到" };
  },

  // 4421：获取坐骑基础详情
  4421: async (payload, helpers) => {
    if (mountWsHandlers[4421]) {
      return await mountWsHandlers[4421](payload, helpers);
    }
    return { act_id: 4421, code: -1, msg: "坐骑处理器未找到" };
  },

  // 4420：训练坐骑
  4420: async (payload, helpers) => {
    if (mountWsHandlers[4420]) {
      return await mountWsHandlers[4420](payload, helpers);
    }
    return { act_id: 4420, code: -1, msg: "坐骑处理器未找到" };
  },

  // 4425：设置坐骑状态（出战/休息）
  4425: async (payload, helpers) => {
    if (mountWsHandlers[4425]) {
      return await mountWsHandlers[4425](payload, helpers);
    }
    return { act_id: 4425, code: -1, msg: "坐骑处理器未找到" };
  },

  // 4419：获取当前出战坐骑信息
  4419: async (payload, helpers) => {
    if (mountWsHandlers[4419]) {
      return await mountWsHandlers[4419](payload, helpers);
    }
    return { act_id: 4419, code: -1, msg: "坐骑处理器未找到" };
  },

  // 4424：获取角色坐骑列表
  4424: async (payload, helpers) => {
    if (mountWsHandlers[4424]) {
      return await mountWsHandlers[4424](payload, helpers);
    }
    return { act_id: 4424, code: -1, msg: "坐骑处理器未找到" };
  },

  // 1297：查看基础装备描述
  1297: async (payload, helpers) => {
    try {
      const { id } = payload || {};

      if (!id) {
        return {
          act_id: 1297,
          code: -1,
          msg: "装备ID不能为空",
        };
      }

      // 负重校验：装备按单件重量
      // 兼容：使用 equipmentBaseService.getEquipmentDetail 返回格式化详情
      const equipDetail = await helpers.equipmentBaseService.getEquipmentDetail(
        id,
        helpers.selectedCharacterId
      );
      const weight =
        Array.isArray(equipDetail) && equipDetail[0]
          ? equipDetail[0].weight || 0
          : 0;
      const { currentWeight, maxWeight } =
        await helpers.characterAttributeService.computeWeights(
          helpers.selectedCharacterId
        );
      if (currentWeight + weight > maxWeight) {
        return {
          act_id: 1297,
          code: -1,
          msg: "负重已满，无法购买",
          data: null,
        };
      }

      if (!equipDetail || equipDetail.length === 0) {
        return {
          act_id: 1297,
          code: -1,
          msg: `装备ID ${id} 不存在`,
        };
      }

      return {
        act_id: 1297,
        code: 0,
        data: equipDetail,
      };
    } catch (error: any) {
      console.error("获取装备描述失败:", error);
      return {
        act_id: 1297,
        code: -1,
        msg: error?.message || "获取装备描述失败",
      };
    }
  },

  // 1064：宝石详情查看
  1064: async (payload, helpers) => {
    try {
      const { id } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1064,
          code: -1,
          msg: "请先选择角色",
        };
      }

      if (!id || typeof id !== "number") {
        return {
          act_id: 1064,
          code: -1,
          msg: "宝石ID不能为空且必须为数字",
        };
      }

      const result = await helpers.gemService.getGemDetail(characterId, id);

      if (result.success) {
        return {
          act_id: 1064,
          code: 0,
          data: result.data,
        };
      } else {
        return {
          act_id: 1064,
          code: -1,
          msg: result.message,
        };
      }
    } catch (error: any) {
      console.error("获取宝石详情失败:", error);
      return {
        act_id: 1064,
        code: -1,
        msg: error?.message || "获取宝石详情失败",
      };
    }
  },

  // 1091：宝石丢弃
  1091: async (payload, helpers) => {
    try {
      const { id } = payload;
      const characterId = helpers.selectedCharacterId;

      if (!characterId) {
        return {
          act_id: 1091,
          code: -1,
          msg: "请先选择角色",
        };
      }

      if (!id || typeof id !== "number") {
        return {
          act_id: 1091,
          code: -1,
          msg: "宝石ID不能为空且必须为数字",
        };
      }

      const result = await helpers.gemService.discardGem(characterId, id);

      if (result.success) {
        return {
          act_id: 1091,
          code: 0,
          data: result.message,
        };
      } else {
        return {
          act_id: 1091,
          code: -1,
          msg: result.message,
        };
      }
    } catch (error: any) {
      console.error("丢弃宝石失败:", error);
      return {
        act_id: 1091,
        code: -1,
        msg: error?.message || "丢弃宝石失败",
      };
    }
  },

  // 1005：属性点分配
  1005: async (payload, helpers) => {
    try {
      const characterAttributeWsHandlers = new (
        await import("./character-attribute-ws-handlers")
      ).CharacterAttributeWsHandlers(
        helpers.characterAttributeService,
        helpers.characterEquipmentService
      );
      return await characterAttributeWsHandlers.handleAttributeAllocation(
        payload,
        helpers
      );
    } catch (error: any) {
      console.error("处理属性点分配失败:", error);
      return {
        act_id: 1005,
        code: -1,
        msg: error?.message || "属性点分配失败",
      };
    }
  },

  // 1137：装备穿戴
  1137: async (payload, helpers) => {
    try {
      const characterAttributeWsHandlers = new (
        await import("./character-attribute-ws-handlers")
      ).CharacterAttributeWsHandlers(
        helpers.characterAttributeService,
        helpers.characterEquipmentService
      );
      return await characterAttributeWsHandlers.handleEquipItem(
        payload,
        helpers
      );
    } catch (error: any) {
      console.error("处理装备穿戴失败:", error);
      return {
        act_id: 1137,
        code: -1,
        msg: error?.message || "装备穿戴失败",
      };
    }
  },

  // 1136：装备卸下
  1136: async (payload, helpers) => {
    try {
      const characterAttributeWsHandlers = new (
        await import("./character-attribute-ws-handlers")
      ).CharacterAttributeWsHandlers(
        helpers.characterAttributeService,
        helpers.characterEquipmentService
      );
      return await characterAttributeWsHandlers.handleUnequipItem(
        payload,
        helpers
      );
    } catch (error: any) {
      console.error("处理装备卸下失败:", error);
      return {
        act_id: 1136,
        code: -1,
        msg: error?.message || "装备卸下失败",
      };
    }
  },

  // 1130：查询装备信息
  1130: async (payload, helpers) => {
    try {
      const characterAttributeWsHandlers = new (
        await import("./character-attribute-ws-handlers")
      ).CharacterAttributeWsHandlers(
        helpers.characterAttributeService,
        helpers.characterEquipmentService
      );
      return await characterAttributeWsHandlers.handleGetEquipmentInfo(
        payload,
        helpers
      );
    } catch (error: any) {
      console.error("查询装备信息失败:", error);
      return {
        act_id: 1130,
        code: -1,
        msg: error?.message || "查询装备信息失败",
      };
    }
  },

  // 1139：查询指定玩家已装备的装备列表 {c:1139, d:{userId}}
  1139: async (payload, helpers) => {
    try {
      const { userId } = payload || {};
      const targetId = Number(userId);
      if (!Number.isFinite(targetId) || targetId <= 0) {
        return { act_id: 1139, code: -1, msg: "用户ID不能为空", data: null };
      }
      // 直接使用服务按指定角色ID获取已装备信息
      const equipmentInfo =
        await helpers.characterEquipmentService.getCharacterEquipment(targetId);
      return { act_id: 1139, code: 0, msg: "ok", data: equipmentInfo };
    } catch (error: any) {
      console.error("查询指定玩家已装备的装备列表失败:", error);
      return {
        act_id: 1139,
        code: -1,
        msg: error?.message || "查询失败",
        data: null,
      };
    }
  },

  // 1477：查询当前负重与总负重
  1477: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) {
        return { act_id: 1477, code: -1, msg: "请先选择角色", data: null };
      }
      const { currentWeight, maxWeight } =
        await helpers.characterAttributeService.computeWeights(characterId);
      return { act_id: 1477, code: 0, data: [currentWeight, maxWeight] };
    } catch (error: any) {
      return {
        act_id: 1477,
        code: -1,
        msg: error?.message || "查询失败",
      };
    }
  },

  // 1480：查看我的房子
  1480: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1480, code: -1, msg: "请先选择角色" };
      const house = await helpers.characterService.getCharacterHouse(
        characterId
      );
      if (!house || !house.lvl) {
        // 根据当前区域名称动态提示
        const areaName = await helpers.characterService.getCharacterAreaName(
          characterId
        );
        return { act_id: 1480, code: 8, msg: `您在${areaName}还没有购买房产` };
      }
      // 仅返回前端期望字段
      return {
        act_id: 1480,
        code: 0,
        data: { r: house.r, lvl: house.lvl, n: house.n },
      };
    } catch (error: any) {
      return { act_id: 1480, code: -1, msg: error?.message || "查询失败" };
    }
  },

  // 1385：购买房子（1级，1980金）
  1385: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1385, code: -1, msg: "请先选择角色" };
      const r = await helpers.characterService.purchaseHouse(characterId);
      if (r.code === 0) return { act_id: 1385, code: 0, data: "购买成功" };
      return { act_id: 1385, code: r.code, msg: r.msg };
    } catch (error: any) {
      return { act_id: 1385, code: -1, msg: error?.message || "购买失败" };
    }
  },

  // 1386：升级房子
  1386: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1386, code: -1, msg: "请先选择角色" };
      const r = await helpers.characterService.upgradeHouse(characterId);
      if (r.code === 0) return { act_id: 1386, code: 0, data: "升级成功" };
      return { act_id: 1386, code: r.code, msg: r.msg };
    } catch (error: any) {
      return { act_id: 1386, code: -1, msg: error?.message || "升级失败" };
    }
  },

  // 1512：查询书房状态（-1 可设置；>0 剩余分钟）
  1512: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1512, code: -1, msg: "请先选择角色" };
      const svc = (helpers as any).houseTrainingService;
      if (!svc?.getLibraryStatus)
        return { act_id: 1512, code: -1, msg: "服务未准备好" };
      const remain = await svc.getLibraryStatus(characterId);
      return { act_id: 1512, code: 0, data: remain };
    } catch (error: any) {
      return { act_id: 1512, code: -1, msg: error?.message || "查询失败" };
    }
  },

  // 1488：查看功房状态/进入（有占用返回 {c,n,t}，否则返回 null）
  1488: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1488, code: -1, msg: "请先选择角色" };
      const svc = (helpers as any).houseTrainingService;
      if (!svc?.getGongfangStatus)
        return { act_id: 1488, code: -1, msg: "服务未准备好" };
      const r = await svc.getGongfangStatus(
        characterId,
        async (cid: number) => {
          try {
            // 复用 gateway 的 getCharacterName 能力不可直接访问，这里通过 characterService 查角色名
            const c = await helpers.characterService.getCharacterById(cid);
            return c?.name || "玩家";
          } catch (_) {
            return "玩家";
          }
        }
      );
      return { act_id: 1488, code: 0, data: r.busy ? r.data : null };
    } catch (error: any) {
      return { act_id: 1488, code: -1, msg: error?.message || "查询失败" };
    }
  },

  // 1483：房屋疗养（按房屋等级每天 1-5 次；恢复主角与背包副将至满状态）
  1483: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1483, code: -1, msg: "请先选择角色" };
      const svc = (helpers as any).houseTrainingService;
      if (!svc?.healAllByHouse)
        return { act_id: 1483, code: -1, msg: "服务未准备好" };
      return await svc.healAllByHouse(characterId);
    } catch (error: any) {
      return { act_id: 1483, code: -1, msg: error?.message || "操作失败" };
    }
  },

  // 1516：功房副将列表（供选择）
  1516: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 1516, code: -1, msg: "请先选择角色" };
      // 规则：
      // 房屋等级≤3：无可选（与前端开关一致）；≥4：开放部分；≥5：全部
      // 这里直接返回玩家的副将列表，前端再做禁用控制
      const listResp = await helpers.deputyGeneralService.getDeputyList(
        characterId,
        false
      );
      // 前端期望：code=0, data=[{name, s, lvl, roleType, id, ...}]
      return { act_id: 1516, code: 0, data: listResp.list };
    } catch (error: any) {
      return { act_id: 1516, code: -1, msg: error?.message || "查询失败" };
    }
  },

  // 6401：炼丹房状态（有人修炼返回 {n,t}，否则 null）
  6401: async (_payload, helpers) => {
    try {
      const svc = (helpers as any).houseTrainingService;
      if (!svc?.getAlchemyStatus)
        return { act_id: 6401, code: -1, msg: "服务未准备好" };
      const characterId = helpers.selectedCharacterId;
      const r = await svc.getAlchemyStatus(characterId, async (cid: number) => {
        try {
          const c = await helpers.characterService.getCharacterById(cid);
          return c?.name || "玩家";
        } catch (_) {
          return "玩家";
        }
      });
      return { act_id: 6401, code: 0, data: r.busy ? r.data : null };
    } catch (error: any) {
      return { act_id: 6401, code: -1, msg: error?.message || "查询失败" };
    }
  },

  // 6404：炼丹可用副将列表（供选择）
  6404: async (_payload, helpers) => {
    try {
      const characterId = helpers.selectedCharacterId;
      if (!characterId) return { act_id: 6404, code: -1, msg: "请先选择角色" };
      const listResp = await helpers.deputyGeneralService.getDeputyList(
        characterId,
        false
      );
      // 仅返回未上阵（pos=0）的副将；前端 DragonChemistDialog 期望字段：id/lvl/name/roleType/s
      const notDeployed = (listResp?.list || []).filter(
        (d: any) => (d?.pos || 0) === 0
      );
      return { act_id: 6404, code: 0, data: notDeployed };
    } catch (error: any) {
      return { act_id: 6404, code: -1, msg: error?.message || "查询失败" };
    }
  },
};
